1

有没有办法将以下 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;
                }
            }
        }
    }
}
4

3 回答 3

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();

您可以使用以下方式代替 join 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();
于 2012-10-16T20:59:44.580 回答
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;
    }

(必须删除一些点道具才能更清晰地做到这一点。)

于 2012-10-16T20:59:36.753 回答
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();
于 2012-10-16T21:02:16.720 回答