Reputation: 4918
I am trying to find a linq query so I can write it in an if statement.
Pseudo code:
IDList is a list of ints List< int >
if (IDList.Contains (Object.Id)) Do something
but I can't seem to work out what need.
In none-linq this works:
foreach(int id in IDList )
{
if (id == Object.Id)
break;
}
but I want it as one line if possible.
I first tried this:
IDList.Contains(Object.Id);
but this throws a compile error
I'm wondering should it be one of these two?
IDList.Any(id => id == Object.Id)
or
IDList.Exists(id => id == Object.Id);
I don't completely understand how the lambdas and things work or the difference between andy and exists so I'm not sure if I'm along the wrong line?
Upvotes: 12
Views: 35351
Reputation: 1972
IDList.Any(id => id == Object.Id)
Is ok, it will return you true
if at least one element, that satisfies your predicate, exists.
Upvotes: 8
Reputation: 7448
You can simply do this:
if (MyList.Any(c => c.Id == MyObject.Id)) { }
Assuming that MyList
is an IEnumerable<T>
(or anything that derives from IEnumerable<T>
) where T is an object that has a property named Id
of the same type of the property Id
on the MyObject
instance.
Upvotes: 27