C#,比较两种不同类型的列表 [英] C#, compare two different type of lists

查看:191
本文介绍了C#,比较两种不同类型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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));

这两个都使用LINQ-如果您以前从未使用过LINQ,则一定要对其进行研究.这非常有用.

Both of these use LINQ - if you haven't come across it before, you should definitely look into it. It's wonderfully useful.

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

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

这篇关于C#,比较两种不同类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆