0

I'm fairly new programing and I had a question.

List A is filled with elements of List B, and I want to create a List C with the missing elements from it, using a variable (that is an int) as a comparison point.

List A is stored on a Session Variable List B is taken from my database this way:

IEnumerable<ListB> Listb = db.ListB; 
List<ListB> Listb = db.ListB.ToList();

I tried this solution (Use LINQ to get items in one List<>, that are not in another List<>), but it didn't work for me, or more probably, I couldn't understand it enough to make it work.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • OP, There is no "List A" in your example. Did you accidentally leave it out? – John Wu Dec 18 '22 at 18:29
  • On my database I have a table, which with the info on ListA, I'm sorry of I didn't specified before, and for the missing elements I meant that ListB is filled with some elements of ListA, and I want ListC to have the element's that are on ListA but not on ListB (Also I used ListA, b, and C here for simplicity's sake, sorry if I make it more confusing, English is not my first language) – Thomas Storandt Dec 18 '22 at 19:36

1 Answers1

3

Hope you can understand this code.

List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<int> list2 = new List<int>() { 1, 2, 3, 4, 5, 6 };

List<int> list3 = list1.Except(list2).ToList();

I have used Except method here. and its work is clear by its name itself. Give me the item from list1 except list2.

More pictorial description by the pic.

enter image description here

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • Well, OP has a `List` not a `List`. So your code will not work if `ListB` doesn't overrride `Equals` and `GetHashCode` or if the same instances are in both lists what is unlikely since the 2nd list comes from a database. `ListB` seems to have an int property that OP wants to use to identify the object. – Tim Schmelter Dec 18 '22 at 18:06
  • @TimSchmelter by the question explanation it looks like OP misunderstood it by List – Vivek Nuna Dec 18 '22 at 18:27
  • @TimSchmelter, yeah, you are right on that one, sorry if I make it confusing – Thomas Storandt Dec 18 '22 at 19:38