Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq select object in List where int in object child List<int> occurs n times

Tags:

c#

linq

I have a List<TestObj> ListOfTestObjs of type

public class TestObj
{
    public List<int> Ints;
}

How do i perform a Linq query that returns an object in the list if the case is that a given integer x occurs n times, and returns null if not? Something like this:

ListOfTestObjs.FirstOrDefault(l => l.Ints == x occurs 3 times in Ints)

Thanks in advance

like image 311
Mike Hawkins Avatar asked Dec 21 '25 17:12

Mike Hawkins


1 Answers

If x is the number you are looking for and n is the number of times it should occur in the inner collection:

ListOfTestObjs.FirstOrDefault(l => l.Ints.Count(i => i == x) == n);
like image 184
Theodoros Chatzigiannakis Avatar answered Dec 23 '25 06:12

Theodoros Chatzigiannakis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!