简体   繁体   中英

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. 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.

        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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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