C#,比较两种不同类型的列表

时间:2014-08-04 13:55:12

标签: c# list object compare

我有对象列表,我有字符串列表。

List<String> states = new List<String>();
states.add("wisconsin");
states.add("Florida");
states.add("new york");

List<Foo> foo = new List<Foo>();
foo.add(new Foo(2000, name1, "wisconsin"));
foo.add(new Foo(1000, name2, "california"));
foo.add(new Foo(300, name3, "Florida"));

一个对象有三个属性: int age,string name和string state。

我将这些对象添加到列表中。第二个列表由&#34;状态&#34;。

组成

我如何比较这两个清单?什么是最好的方法呢? 我想知道其中一个对象是否具有相同的&#34; state&#34;,其他列表包含哪个。 请指导我。

1 个答案:

答案 0 :(得分:4)

听起来你想要这样的东西:

List<Person> people = ...;
List<string> states = ...;

var peopleWithKnownStates = people.Where(p => states.Contains(p.State));

或者只是为了找出任何的人是否已知状态:

var anyPersonHasKnownState = people.Any(p => states.Contains(p.State));

这两个都使用LINQ - 如果你以前没有遇到它,你一定要调查它。它非常有用。

您可能希望将states更改为HashSet<string>,以便Contains操作更快。