简体   繁体   中英

Count the number of Enum values in list using Linq

I have an enum like this :

public enum PlayResultEnum
{
    First, Cooperate, Defect
}

I create a list of this:

    public List<PlayResultEnum> Agent1Result=new List<PlayResultEnum>();
    public List<PlayResultEnum> Agent2Result=new List<PlayResultEnum>();

I need to count ,for example First values in my list using lambda (Linq) .

How can I do that?

var count = Agent1Result.Count(c => c == PlayResultEnum.First);

Or another way:

var count = Agent1Result.Count(c => (int)c == 0);

It will work if your PlayResultEnum.First is the first value and you didn't set another value manually.From documentation

By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.

It's not entirely clear what you're asking...

If you want to know the number of items in the list, you don't need linq, just do:

var count = Agent1Result.Count;

If you want to know the number of items in the list of a specific type, do:

var count = Agent1Resut.Count(x => x == PlaEnumResult.First);

For getting all the occurrences, you would do something like this:

Dictionary<PlayResultEnum, int> countResults 
           = Agent1Result.GroupBy(x => x)
                         .ToDictionary(x => x.Key, y => y.Value.Count);

Now you can get the occurrences for every enum value:

Console.WriteLine(countResults[PlayResultEnum.First]);

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