I have the following code
var myList = new List<int>() {10, 10, 10, 9, 15};
var groupedMyList = myList.GroupBy(i => i).ToList();
var hasFourOfSameValue = groupedMyList.Select(g => g.Count() == 4).Any();
The issue is that hasFour comes back as true. I expect it to be false as there is maximum three ints with the same value in the list? (I suspect I go wrong in the groupby call but I can't figure out how to change it).
Question preamble: I want to use LINQ method syntax not LINQ query syntax.
You want:
var hasFourOfSameValue = groupedMyList.Any(grp => grp.Count() == 4);
Any()
returns true if the input sequence contains any elements.
The expression groupedMyList.Select(g => g.Count() == 4)
returns { false, false, false }
. And calling any on a non-empty sequence is true. You want:
var hasFourOfSameValue = groupedMyList.Any(g => g.Count() == 4);
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.