简体   繁体   English

如何将嵌套的 foreach 循环转换为 C# 中的 LINQ 查询

[英]How to convert nested foreach loop into LINQ query in C#

How to convert nested foreach loop into LINQ query in C# and i want to return list after querying the result.如何在 C# 中将嵌套的 foreach 循环转换为 LINQ 查询,我想在查询结果后返回列表。 List will return vale and description.列表将返回值和描述。 below code is working fine but i need to convert these 2 foreach loops into a single LINQ query.下面的代码工作正常,但我需要将这 2 个 foreach 循环转换为单个 LINQ 查询。

        List<ListItem> listCodes = new List<ListItem>();
    
        foreach (var staticValueGroupMember in staticValueGroupMembers)
        {
            string description = string.Empty;
            if (staticValueGroupMember != null)
            {
                foreach (var staticValue in staticValues)
                {
                    if (staticValue.Value == staticValueGroupMember.MemberCode.ToString())
                    {
                        description = staticValue.Description;
                        break;
                    }

                }

                listCodes.Add(new ListItem() { Value = staticValueGroupMember.MemberCode.ToString(), Description = description });
            }
        }

        return listCodes;

This is pretty much a direct translation.这几乎是直接翻译。

List<ListItem> listCodes =
(
    from staticValueGroupMember in staticValueGroupMembers
    where staticValueGroupMember != null
    join staticValue in staticValues
        on staticValueGroupMember.MemberCode.ToString() equals staticValue.Value
    select new ListItem()
    {
        Value = staticValueGroupMember.MemberCode.ToString(),
        Description = staticValue.Description
    }
).ToList();

Try the code below:试试下面的代码:

var result = staticValueGroupMembers
    .Where(gm => gm != null)
    .Join(staticValues,
        outer => outer.MemberCode.ToString(),
        inner => inner.Value,
        (outer, inner) => new ListItem()
        {
            Value = outer.MemberCode.ToString(),
            Description = inner.Description
        })
    .ToList();

Here is the detail of the Join method.这是Join方法的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM