简体   繁体   中英

Count the number of elements in a list of lists with Linq

I'd like to use some LINQ in my C# code to improve readability.

Given

private IDictionary<T, ICollection<E>> myDict;

a Dictionary with collections as values, how to determine the total amount of elements in all collections with LINQ?

public int AmountElements 
{
   get
   {
     return ??;
   }
}

要获取字典值中的元素总数:

myDict.Values.Sum(collection => collection.Count);

You can do as follows:

var count = myDict.SelectMany(d => d.Value).Count();

So you can write your AmountElements property as follows:

 public int AmountElements => myDict.SelectMany(d => d.Value).Count();

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