简体   繁体   中英

Can I convert Dictionary loop inside of a foreach loop into a LINQ statement

If possible please help me convert these nested loops into a LINQ statement

Thank you very much for your help!

    public static List<Term> GetTermsByName(this IEnumerable<Term> terms, Dictionary<string, string> termInfo)
    {
        List<Term> termList = new List<Term>();
        foreach (Term term in terms)
        {
            foreach (var value in termInfo.Values)
            {
                if (term.Name == value)
                {
                    termList.Add(term);
                }
            }
        }

        return termList;
    }

Maybe Contains method is what you are after

Determines whether a sequence contains a specified element.

The following can be read as, Filter all Terms where the Term.Name exists in the dictionary Values

var values = termInfo.Values;
var result = terms.Where(term => values.Contains(term.Name));
                  .ToList();

// or

var result = terms.Where(term => termInfo.Values.Contains(term.Name));
                  .ToList();

You're losing the plot of the dictionary a bit here, don't you think? The speediness is in using the keys. However, you can still do better than a nested foreach or an inline linq equivalent with where and contains . Use a join to at least improve your efficiency.

var termList = (from term in terms
                join value in termInfo.Values 
                on term.Name equals value 
                select term)
               .Distinct() // if there are duplicates in either set 
               .ToList();

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