Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list contains an ID in linq

Tags:

c#

asp.net

linq

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?

like image 754
Bex Avatar asked Oct 28 '11 12:10

Bex


2 Answers

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.

like image 69
Matteo Mosca Avatar answered Nov 19 '22 22:11

Matteo Mosca


 IDList.Any(id => id == Object.Id)

Is ok, it will return you true if at least one element, that satisfies your predicate, exists.

like image 39
Dmitriy Avatar answered Nov 19 '22 20:11

Dmitriy