Sunday, March 27, 2011

How can I get data from a list with a where clause to another list?

Hi,

I have a list with multiple class that contain a Property that is an Integer (Id).

I have a List of Integer too.

Now, I would like to trim the List of my object to only those class that has the Property in the list of the integer.

Example:

List of MyObject
[MyObjectA].Id = 1
[MyObjectB].Id = 2
[MyObjectC].Id = 3
[MyObjectD].Id = 4

List of Integer
1
2

Final list should be 
[MyObjectA]
[MyObjectB]

How can I do it?

From stackoverflow
  • You could use contains:

    var finalList = originalList.Where(x => idList.Contains(x.Id)).ToList();
    

    Or a join:

    var finalList = (from entry in originalList
                    join id in idList on entry.Id equals id
                    select entry).ToList();
    
    shahkalpesh : did you mean entry.Id instead of x.Id? (in case of using join)
    David Basarab : I like solution 1 the best. The joins are nice, but I like the readability of the first one better.
    Jon Skeet : @shahkalpesh: Fixed, thanks. @Longhorn213: The second one will be significantly quicker if idList ends up being very big. It basically builds a hash map instead of doing a linear scan for every entry.
    Daok : This is what I needed. Thx
  • How about:

    list.RemoveAll(x => list2.IndexOf(x.Id) >= 0);
    
  • This should do it:

    // Assume objList is IEnumerable<MyObject> and intList is IEnumerable<int>.
    IEnumerable<MyObject> intersection =
      from obj in objList
        join i in intList on obj.Id equals i
      select obj
    

    Mind you, if multiple objects have the same id, or the id is listed multiple times in the list and one object corresponds to it, the object will show up more than once in the resultant list.

    I think the group is better for larger lists, as some of the other solutions will iterate over the lists multiple times to search for the corresponding object.

0 comments:

Post a Comment