我有两个班,比如:
public class Person
{
public long Id { get; set; }
public string Name { get; set; }
}
public class Vampire
{
public long Id { get; set; }
}
然后,我有两个名单,一个人名单和一个吸血鬼名单。所有吸血鬼都是人。
我需要的是两个被感染和未感染的儿童名单。我正在使用for构建两个列表,但我知道可以使用linq或其他东西。
任何帮助?
答案 0 :(得分:3)
这样的事情:
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));
答案 1 :(得分:1)
我会选择以下内容:
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
{
}
答案 2 :(得分:0)
如果只有一个人可以成为Vapire,你可以从Person继承吸血鬼,然后遍历所有人,看看他们是否是吸血鬼;如果是 - &gt;添加到吸血鬼列表,否则添加到非吸血鬼列表。
答案 3 :(得分:0)
试试这个:
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!");
}
希望它有用。