I'm trying to learn lambda operations and I can't figure out how to get this to work. What I have gets the opposite of what I need, but I can't figure out what I need to do to reverse it.
DataTable table1;
List<string> list1;
var duplicates = list1.AsEnumerable()
.Where(r => table1.AsEnumerable()
.Any(r2 => r2["ID"] as string == r.ToString()));
I basically have a shopping cart which in this example is table1
. When the user goes to add an item to their cart, I want to make sure said items don't already exist in their cart. So my list1 has the ID's of the items they are about to put in their cart and the datatable is their current cart contents, and has a column called ID
. So I would like to have the result be the remaining items of list1
that were not found in the ID
column of my table.
The above will get all the items that are in the shopping cart.
I thought just changing the ==
to !=
would work, but it does not. I found a bunch of different threads that had similar problems, but all the ones I found were comparing two objects that were the same, like two datatables with the same columns or two List<string>
objects. They were saying to use the keyword Except
. Every time I tried to duplicate these results, I had an issue with the syntax.
Here was one thing I tried from another thread, but it gives me a syntax error for the select statement. I tried to base this off of the answer in the following thread: Use LINQ to get items in one List<>, that are not in another List<>
var result = list1.Where(p => !table1.Select(p2 => p2["RegID"] == p.ToString()));
I would appreciate any help you can give me!
--Joseph
edit Here is my working code.
DataTable table1;
List<string> list1;
var duplicates = list1.AsEnumerable()
.Where(r => table1.AsEnumerable()
.All(r2 => r2["ID"] as string != r.ToString()));