将多级for循环转换为linq或lambda表达式

时间:2012-10-17 01:42:19

标签: c# linq lambda

我已经发布了相关问题如下:

replace 3 levels of nested for loops by efficient code possibly linq

但是因为我对Linq或Lambda表达不满意......我不确定如何进一步扩展它。

我有一个稍微不同的3级嵌套for循环,我不知道如何将它转移到Linq或Lambda表达式中。我的工作任务是为linq中的以下内容提供更有效的替换代码lambda表达..请帮忙。感谢..

public static void CompareEntities(
    out EntityCollection<StringResourceEntity> entitiesDifference,
    EntityCollection<StringResourceEntity> entitiesLargerSet,
    EntityCollection<StringResourceEntity> entitiesSmallerSet)
{
    var diff = new EntityCollection<StringResourceEntity>();
    string defaultCulture = LocalizationConfiguration.DefaultCulture;

    foreach (StringResourceEntity entityLargerSet in entitiesLargerSet)
    {
        bool entityMatch = false;
        foreach (StringResourceEntity entitySmallerSet in entitiesSmallerSet)
        {
            if (entityLargerSet.Key.Equals(entitySmallerSet.Key))
            {
                foreach (var stringResValSmall in entitySmallerSet.StringResourceValues)
                {
                    if (stringResValSmall.Culture.Equals(defaultCulture) &&
                        stringResValSmall.Value.Length > 0)
                    {
                        entityMatch = true;
                    }
                }
            }
        }

        if (entityMatch == false)
        {
            diff.Add(entityLargerSet);
        }
    }

    entitiesDifference = diff;
}

3 个答案:

答案 0 :(得分:2)

我更喜欢lambda表达式,因为我发现它们非常易读。我会做这样的事情:

var diff = entitiesLargerSet.Where(large => 
    !entitiesSmallerSet.Any(small => 
        small.Key.Equals(large.Key) 
        && small.StringResourceValues.Any(x => 
            x.Culture.Equals(defaultCulture) && x.Value.Length > 0))).ToList();

缩进很糟糕,但要把它变成你自己的。

答案 1 :(得分:1)

这可能会让你开始。如果不创建所有类的骨架版本,则很难判断代码是否正确编译或将产生正确的结果:

var diff = entitiesLargerSet.Except(
            from x in entitiesLargerSet
            from y in entitiesSmallerSet
            where x.Key.Equals(y.Key)
            from z in y.StringResourceValues
            where stringResValSmall.Culture.Equals(defaultCulture)
               && stringResValSmall.Value.Length > 0
            select x);

答案 2 :(得分:1)

string defaultCulture = LocalizationConfiguration.DefaultCulture;
var diff = (from x in entitiesLargerSet
            let matches = entitiesSmallerSet.Where(y =>
                 x.Key.Equals(y.Key) &&
                 y.StringResourceValues.Any( z => z.Culture.Equals(defaultCulture) &&
                                                  z.Value.Length > 0))
            where matches.Any() == false
            select x).ToList();
// TODO: Convert List to EntityCollection