2

I have a custom list List. which returns all items. The structure of Info is as follows:

public class Info
  {
    public string Code { get; set; }
    public string ClinicianDescription { get; set; }
  }

I want to exclude any Info objects from the list where the Code property equels any value in a separate List.

Just after a clean way to do this, i've tried using .Except(), but i would have to convert the List into the same object which seems incorrect.

I've tried something like this so far:

List<int> ids = contactList;
var List<Info> test = info.RemoveAll(x => ids.Any(i => i == x.Code));
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
the_tr00per
  • 439
  • 7
  • 23

4 Answers4

7

You could use Except, although this takes an IEnumerable, not a predicate, and you need to be careful when using this with custom classes when determining the equivalence of two objects

var blackListCodes = contactList.Select(i => i.ToString()); 
var test = info.Except(info.Where(i => blackListCodes.Contains(i.Code)));

But as Tomassino has pointed out, this can be inverted and simplified as:

var test = info.Where(i => !blackListCodes.Contains(i.Code))

Note that this will project a new Enumerable, rather than change elements in the existing info, which RemoveAll does.

Just some other points - re your code sample:

  • As others have pointed out, the type used in the Code match needs to be compatable in the comparison, i.e. you can't compare string Code with the ints in ids. Here, because we're using .Except on the same source collection, comparison of elements will work as expected, even if it relies on default reference equality (since it's the same element reference in both IEnumerables).

  • RemoveAll returns an int representing the number of elements pruned from the list - the result can't be assigned to another List.

StuartLC
  • 104,537
  • 17
  • 209
  • 285
2

You can also use this approach:

 List<Info> info = new List<Info>();
 //fill info with objects

 List<string> excludeCodes = new List<string>();
 //fill excludeCodes with values

 var result = info.Where(i => !excludeCodes.Contains(i.Code)).ToList();
Tomas Chabada
  • 2,869
  • 1
  • 17
  • 18
0

Why can't you use Contains() like

List<Info> test = info
                     .Where(i => !ids.Contains(i.Code)).ToList();
Rahul
  • 76,197
  • 13
  • 71
  • 125
0

you try to compare string with int!

Deidah
  • 11
  • 4