从 C# 中的列表中获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17350727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:16:05  来源:igfitidea点击:

Get data from a list in C#

c#listclass

提问by Eknoes

I've created a list of a class. Here you can see the code:

我创建了一个班级列表。在这里你可以看到代码:

public class People{
        public string name;
        public int age;     
    }   

public List<People> peopleInfo = new List<People>();

My problem is that I have for example a name and now I want to know the age. How do I get this data? I can get a name or the age on a specific position by this:

我的问题是,例如我有一个名字,现在我想知道年龄。我如何获得这些数据?我可以通过以下方式获得特定职位的姓名或年龄:

int pos = peopleInfo[0].name;

But how I can do it the inverted way and get the position of name? When I have this it easy to get the age.

但是我怎样才能以倒置的方式做到这一点并获得名称的位置?当我有这个时,很容易变老。

回答by p.s.w.g

You can use the FindIndexmethod:

您可以使用以下FindIndex方法:

var searchForName = "John";
int index = peopleInfo.FindIndex(p => p.name == searchForName);

This will return the index of the first person in the list whose nameproperty is equal to "John". Of course there may be many people with the name "John", and you may want to find all of them. For this you can use LINQ:

这将返回列表中第一个name属性等于 的人的索引"John"。当然,可能有很多人有这个名字"John",你可能想找到所有的人。为此,您可以使用 LINQ:

IEnumerable<int> indexes = peopleInfo.Select((p, i) => new { p, i })
                                     .Where(x => x.p.name == searchForName)
                                     .Select(x => x.i);
foreach(int i in indexes)
{
    peopleInfo[i].age ...
}

But if you don't really need the index, this is muchmore simple:

但如果你真的不需要索引,这简单得多

foreach(People person in peopleInfo.Where(p => p.name == searchForName))
{
    person.age ...
}

回答by John Kraft

int index = peopleInfo.FindIndex(p => p.name == "TheName");

or, you could just find the object directly...

或者,您可以直接找到对象...

People person = peopleInfo.FirstOrDefault(p => p.name == "TheName");

回答by Alexander

You can use FindIndex to find person by name. But in case if this operation will be frequent, you may hit performance problems, as each FindIndex call will look up through entire list, one record by one.

您可以使用 FindIndex 按姓名查找人员。但是,如果此操作频繁发生,您可能会遇到性能问题,因为每个 FindIndex 调用都会逐条查找整个列表。

Probably in this situation it would be better to build dictionary of persons by name. Or even dictionary of age by name, if the only thing you need is a person's age.

可能在这种情况下,最好按姓名建立人名词典。或者甚至是按姓名列出的年龄词典,如果您只需要一个人的年龄。

Also, consider case when person name is not unique.

另外,请考虑人名不唯一的情况。

List<People> peopleInfo = new List<People>() { ... };
Dictionary<string, People> map = peopleInfo.ToDictionary(p => p.name);
People p = map["John"];