MrProgram
MrProgram

Reputation: 5242

Get elements in list by condition against other list

I have two lists of the same object, and they are of different sizes.

I wan't all in objects List1 where tmDate does not exist in List2.

public class MyObj
{
    public MyObj(DateTime tmDate)
    {
        this.tmDate = tmDate;
    }
    public DateTime tmDate { get; set; }
}

var List1 = new List<MyObj>();
        var List2 = new List<MyObj>();

        List1.Add(new MyObj(new DateTime(2015, 01, 01)));
        List1.Add(new MyObj(new DateTime(2015, 01, 02)));
        List1.Add(new MyObj(new DateTime(2015, 01, 03)));

        List2.Add(new MyObj(new DateTime(2015, 01, 01)));
        List2.Add(new MyObj(new DateTime(2015, 01, 02)));

        var notMatchingObj =
            List1.Where(
                l1 => List2.Any(l2 => l2.tmDate != l1.tmDate));

This code gives me wrong output..I only want MyObj with tmDate 2015-01-03 in this case

Upvotes: 1

Views: 217

Answers (2)

Ravi H M
Ravi H M

Reputation: 1

Try

var notMatchingObj =
                from list1 in List1
                where (!List2.Any(l2 => l2.tmDate == list1.tmDate))
                select new { list1.tmDate };

Upvotes: -1

Christos
Christos

Reputation: 53958

You could try this one:

var result = list1.Where(item=>!list2.Any(item2=>item2.tmDate==item.tmDate));

This list2.Any(item2=>item2.tmDate==item.tmDate) returns true if there is any item in the list2 with the same date with the item. Otherwise it returns false. Taking it's negation, we get that we want.

On the other hand this List2.Any(l2 => l2.tmDate != l1.tmDate) returns true if any item found in List2, whose date is not the same with the date of l1. This doesn't mean that an object with the same date with the l1 doesn't exist. The above will return true if the first item you check has date different with l1. However an item in List2 may exist with the same date with l1.

Upvotes: 3

Related Questions