tags:

views:

677

answers:

4

I have filled List<Object1> Object 1 contain 2 fields (int id & string name)

Also i Have IEnumerable<Object2> Generated by linq2sql. With fields (id, name)

i need to get items from List<Object1> which Id's are absent in IEnumerable<Object2>. by Key Field = id (like where in in sql..)

i used code like

IEnumerable Object2
List<Object1> excepted =  Object2.Where(t => obj1.Contains == t.Id);

Thank you!

+4  A: 

How about:

HashSet<string> knownIds = new HashSet<string>(list2.Select(x => x.Id));
var exceptions = list1.Where(x => !knownIds.Contains(x.Id));

As Earwicker rightly says, this will just give an IEnumerable<Object1> - if you need a list, change the second line to:

var exceptions = list1.Where(x => !knownIds.Contains(x.Id)).ToList();
Jon Skeet
+2  A: 

Hi!

You can achieve this by the following way.

var excepted = objects1.Where(o1 => !objects2.Select(o2 => o2.Id).Contains(o1.Id));

Best Regards

Oliver Hanappi
I think there is a small mistake:var excepted = objects1.Where(o => !objects2.Select(i => i.ID).Contains(o.ID));
Sessiz Saat
A: 

Further to Jon Skeet's answer, you would need the ToList() extension method at the end of your expression, to turn it into a List.

Daniel Earwicker
+2  A: 

I'm surprised nobody has suggested join:

var excepted = (from o1 in List1
                join o2 in List2
                  on o1.Id equals o2.Id into j
                where !j.Any() // j is empty
                select o1
                ).ToList();

Perhaps marginally less as efficient than Jon's HashSet solution, but query syntax is fun.

dahlbyk