访问C#中的List结构项 [英] access to item of List structure in C#
本文介绍了访问C#中的List结构项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我的结构如下:
如何在列表中找到类型为结构的项目?
(don'使用For循环)
Hi all,
I have structure as below:
how to find item in list with type is structure?
(don't use For loop)
struct person{
public int age;
public string name;
}
public list<person> lstPerson;
public void getListPerson(){
lstPerson = new list<person>();
lstperson.Add(New person{age = 10, name="John"});
lstperson.Add(New person{age = 20, name="John1"});
lstperson.Add(New person{age = 30, name="John2"});
lstperson.Add(New person{age = 40, name="John3"});
lstperson.Add(New person{age = 50, name="John4"});
lstperson.Add(New person{age = 60, name="John5"});
lstperson.Add(New person{age = 70, name="John6"});
}
public person searchPerson(string name){
// how to find person with name is John3 in lstPerson?(don't use loop: For or While)
}
推荐答案
尝试:
Try:
person p = lstPerson.Where(p => p.name == "John3").FirstOrDefault();
if (p != null)
{
...
}
[edit]
适用于课程,而不是结构 - 抱歉,我没有注意到。
[edit]
That works for classes, not structs - sorry, I didn't notice.
List<person> matches = lstPerson.Where(p => p.name == "John3").ToList();
if (matches.Count >= 1)
{
person p = matches[0];
...
}
[.edit]
[.edit]
public person searchPerson(string name)
{
var objPers = lstPerson.Where(_ => _.name == name).FirstOrDefault();
return objPers;
}
public person searchPerson(string name){
person _person = lstPerson.Where(x => x.name == name).FirstOrDefault();
return _person;
}
这篇关于访问C#中的List结构项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文