用有效的代码替换3级嵌套的for循环 [英] replace 3 levels of nested for loops by efficient code possibly linq

查看:106
本文介绍了用有效的代码替换3级嵌套的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以将以下3个级别的嵌套for循环替换为更有效或更简洁的代码? linq能够使它更高效,更易于阅读吗?

Is there a way of replacing following 3 levels of nested for-loops into more efficient or cleaner code? Would linq be able to make it more efficient and easy to read?

请帮助.谢谢

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;
                }
            }
        }
    }
}

推荐答案

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

这篇关于用有效的代码替换3级嵌套的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆