C#, compare two different type of lists

ε祈祈猫儿з 提交于 2019-12-11 09:32:28

问题


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.


回答1:


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. It's wonderfully useful.

You might want to change your states to a HashSet<string> so that the Contains operation is quicker though.



来源:https://stackoverflow.com/questions/25120386/c-compare-two-different-type-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!