2012-10-16 61 views
1

有沒有一種方法可以將嵌套for循環的以下3級替換爲更高效或更簡潔的代碼? linq能夠使它更高效且易於閱讀嗎?用高效代碼替換3級嵌套for循環可能linq

請幫忙。由於

bool myMatch = false; 

foreach (MyEntityClass entitySmallerSet in entitiesSmallerSet) 
{ 
    if (entityLargerSet.Key.Equals(entitySmallerSet.Key)) 
    { 
     foreach (var stringResValLarge in entityLargerSet.StringResourceValues) 
     { 
      foreach (var stringResValSmall in entitySmallerSet.StringResourceValues) 
      { 
       if (stringResValSmall.Culture.Equals(stringResValLarge.Culture) 
        && stringResValSmall.Value.Equals(stringResValLarge.Value)) 
       { 
        myMatch = true; 
       } 
      } 
     } 
    } 
} 
+0

entityLargerSet的定義在哪裏? –

+0

您是否嘗試過使用連接? –

+0

沒有格式化,沒有上下文,只是垃圾... –

回答

9
bool myMatch = entitiesSmallerSet 
    .Where(e => entityLargerSet.Key.Equal(e.Key)) 
    .SelectMany(e => e.StringResourceValues) 
    .Join(entityLargerSet.StringResourceValues, small => new { Culture = small.Culture, Value = small.Value }, large => new { Culture = large.Culture, Value = large.Value }, (s, l) => new object()) 
    .Any(); 

取而代之的是加入您可以使用Intersect

bool myMatch = entitiesSmallerSet 
    .Where(e => entityLargerSet.Key.Equal(e.Key)) 
    .SelectMany(e => e.StringResourceValues) 
    .Select(e => new { Culture = e.Culture, Value = e.Value }) 
    .Intersect(entityLargerSet.StringResourceValues.Select(l => new { Culture = l.Culture, Value = l.Value })) 
    .Any(); 
+0

+1,因爲它非常優雅,並且一找到一場比賽就會中斷。原來的解決方案會一遍又一遍地循環,即使'match'長時間處於'true'狀態。 –

+0

李,感謝您的答案..我將如何確定entityLargerSet這是從實體SmallSet失蹤? –

0

ReSharper的這是否與它:

bool myMatch = false; 
    foreach (var stringResValLarge in 
    from entitySmallerSet 
    in entitiesSmallerSet.Where(entitySmallerSet => entityLargerSet.Key.Equals(entitySmallerSet.Key)) 
    from stringResValLarge in entityLargerSet 
    from stringResValSmall in entitySmallerSet 
    where stringResValSmall.Equals(stringResValLarge)&& stringResValSmall.Equals(stringResValLarge) 
    select stringResValLarge) 
    { 
     myMatch = true; 
    } 

(不得不刪除一些點道具得到ReSharper的到做的事情。)

+0

-1格式化 –

+1

@ L.B我就像......真的嗎?格式化?然後我滾動.. – Eonasdan

+0

哈哈,不知道那裏的所有空白來自哪裏。 –

0

你可以使用這個想法(僞代碼):

var myMatch = (from se in entitiesSmallerSet 
       where e.Key.Equals(entitySmallerSet.Key) 
       from seVal in se.StringResourceValues 
       from leVal in entityLargerSet.StringResourceValues 
       where seVal.Culture.Equals(leVal.Culture) 
        && leVal.Value.Equals(leVal.Value) 
       select seVal).Any();