user989818
user989818

Reputation:

get elements from list based on another list

I got two classes, like:

public class Person
{
    public long Id { get; set; }
    public string Name { get; set; }
}

public class Vampire
    {
    public long Id { get; set; }
}

Then, I have two lists, a list of persons and a list of vampires. All vampires are persons.

What I need is two children lists of persons, infected and notInfected. I'm building the two lists with a for, but I know it's possible using linq or something.

Any help?

Upvotes: 0

Views: 136

Answers (4)

Greg Smith
Greg Smith

Reputation: 2469

Try this:

var people = new List<Person>
             {
                 new Person {Id = 1, Name = "John"},
                 new Person {Name = "Dave", Id = 2},
                 new Person {Id = 3, Name = "Sarah"}
             };

var vamps = new List<Vampire> {new Vampire {Id = 1}};

var theInfected = people.Where(p => vamps.Select(v => v.Id).Contains(p.Id));

var theAfraid = people.Except(theInfected);

foreach (var person in theInfected)
   {
       System.Console.WriteLine(person.Name + " Is Infected!");
   }

foreach (var person in theAfraid)
  {
     System.Console.WriteLine(person.Name + " Is Afraid!");
  }

Hope it's helpful.

Upvotes: 0

Magnus
Magnus

Reputation: 46909

I would go with something like the following:

void Main()
{
    var list = new List<Person>(){ new Person(){ Id = 1 }, new Vampire(){ Id = 2 } };
    var infected    = list.Where (x => x is Vampire);
    var notInfected = list.Except(infected);
}

public class Person
{
    public long Id { get; set; }
    public string Name { get; set; }
}

public class Vampire : Person
{
}

Upvotes: 1

Attila
Attila

Reputation: 28762

If only a person can be a Vapire, you could inherit Vampire from Person and then iterate through all persons and see if they are Vampires; if yes -> add to Vampire list, otherwise to non-Vampire list.

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160852

Something like this:

var vampireIds = new HashSet<long>(vampireList.Select(x => x.Id));
var infectedPersons = personList.Where(x => vampireIds.Contains(x.Id));
var regularPersons = personList.Where(x => !vampireIds.Contains(x.Id));

Upvotes: 3

Related Questions