3

I have two lists (for example):

var NewIDs = new List<string>();
NewIDs.AddRange(...some values...);

var OldIDs = new List<some type>()
OldIDs.AddRange(...some values...);

I need to return the OldIDs list, which contains only values from the first one. I do it this way:

var newList = OldIDs.Where(p => p.Id.All(x => NewIDs.Contains(x.ToString()))).ToList();

But it returns count=0;

EDIT 1: NewIDs it's only List of strings, but OldIDs it's some structure, which have an Id propery

EDIT 2: It works this way:

var newList = new List<MyType>();
 foreach (var res in NewIDs)
   {
     newList.AddRange(OldIDs.Where(a => a.Id == res));
   }

I need to rewrite it without foreach, only using LINQ

Mia
  • 433
  • 4
  • 11
  • 25

2 Answers2

11

Use Enumerable.Intersect:

var newList = OldIDs.Intersect(NewIDs).ToList();

If OldIDs contains a custom object with an Id property:

var newList = OldIDs.Where(x => NewIDs.Contains(x.Id)).ToList();

another, possibly more efficient way using Join:

var oldInNew = from old in OldIDs
               join newID in NewIDs 
               on old.Id equals newID
               select old;
var newList = oldInNew.ToList();
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • second variant also returns count=0. NewIDs it's only List of strings, but OldIDs it's some structure, which have an Id propery – Mia Dec 10 '14 at 11:51
  • @coderman: then `OldIDs` doesn't contain objects which `Id` is contained in `NewIDs`. – Tim Schmelter Dec 10 '14 at 11:53
  • Could you check **EDIT 2**, please – Mia Dec 10 '14 at 12:00
  • @coderman: the EDIT 2-code does not the same. It will add duplicate objects if the ID in `NewIDs` repeats. It's also less efficient. But apart from that both should work. Can you show the class and some sample data which shows the issue? I have added another [more efficient](http://stackoverflow.com/questions/5551264/why-is-linq-join-so-much-faster-than-linking-with-where) way. – Tim Schmelter Dec 10 '14 at 12:21
2

You want to use Intersect(), try the following:

var intersectedList = NewIDs.Intersect(OldIDs).ToList();
Ben Robinson
  • 21,601
  • 5
  • 62
  • 79