是否有可能通过Linq实现这种转换?

时间:2017-12-18 16:52:08

标签: c# linq

foreach (var mkTPL in personalTemplate.MarketsType) {
    foreach (var mkDB in currentPrintRow.Markets) {
        if (mkTPL.IDMarketType == mkDB.IDMarketType) {
            foreach (var selTPL in mkTPL.Selections) {
                foreach (var selDB in mkDB.Selections) {
                    if (selTPL.IdSelectionType == selDB.IdSelectionType) {
                        selTPL.OddOrResultValue = selDB.OddOrResultValue;
                    }
                }
            }
        }
    }
}

这是我自己达成的解决方案

foreach (var mkTPL1 in personalTemplate.MarketsType)
            {
                foreach (var selTPL in mkTPL1.Selections)
                {
                    selTPL.OddOrResultValue = (from mkTPL in personalTemplate.MarketsType
                        join mkDB in currentPrintRow.Markets on mkTPL.IDMarketType equals mkDB.IDMarketType
                        from selDB in mkDB.Selections
                        where selTPL.IdSelectionType == selDB.IdSelectionType
                        select selTPL.OddOrResultValue).SingleOrDefault();
                }
            }

1 个答案:

答案 0 :(得分:1)

你应该能够“平坦化”#34;这些foreach循环与LINQ的连接。如果你有大量数据,这应该加快它们的速度(以使用更多内存为代价)。

var pt2pr =
    from mkTPL in personalTemplate.MarketsType
    join mkDB in currentPrintRow.Markets on mkTPL.IDMarketType equals mkDB.IDMarketType
    select new { PersonalTemplate = mkTPL, PrintRow = mkDB };
foreach (var s in pt2pr.Select(p =>
    from selTPL in p.PersonalTemplate.Selections
    join selDB in p.PrintRow.Selections on selTPL.IdSelectionType equals selDB.IdSelectionType
    select new { selTPL, selDB }
)) {
    s.selTPL.OddOrResultValue = s.selDB.OddOrResultValue;
}

您可以将LINQ连接组合到一个语句中,但使用两个单独的连接看起来更具可读性。