[英]C#, compare two different type of lists
I have list of objects and I have list of strings. 我有对象列表,有字符串列表。
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"));
An object have three properties: int age, string name and string state. 一个对象具有三个属性:整数年龄,字符串名称和字符串状态。
and I have added these objects to the list. 并且我已将这些对象添加到列表中。 Second list consists of string of "states".
第二个列表由“状态”字符串组成。
How I can compare these two lists? 如何比较这两个列表? What is best way to do it?
最好的方法是什么? I want to know if one of objects have same "state", which other list consist.
我想知道对象中的一个是否具有相同的“状态”,其他哪个列表组成。 Please guide me.
请指导我。
It sounds like you want something like: 听起来您想要这样的东西:
List<Person> people = ...;
List<string> states = ...;
var peopleWithKnownStates = people.Where(p => states.Contains(p.State));
Or just to find if any of the people have known states: 或者只是为了找到如果任何人有已知状态:
var anyPersonHasKnownState = people.Any(p => states.Contains(p.State));
Both of these use LINQ - if you haven't come across it before, you should definitely look into it. 两者都使用LINQ-如果您以前从未接触过LINQ,则绝对应该对其进行研究。 It's wonderfully useful.
非常有用。
You might want to change your states
to a HashSet<string>
so that the Contains
operation is quicker though. 您可能需要将
states
更改为HashSet<string>
以便Contains
操作更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.