[英]Finding an index in a list of generic objects with multiple conditions
如果我有一个看起来像这样的课程:
class test
{
public int ID { get; set; }
public int OtherID { get; set; }
}
并列出这些对象:
private List<test> test = new List<test>();
如果我想在其中找到索引,我会写:
int index = test.FindIndex(item => item.ID == someIDvar);
但是现在我想知道是否可以在不编写其他函数的情况下使用它来制作多个条件? 就像我是否要检查ID是否与var匹配,OtherID是否与另一个匹配?
试试这个:
int index = test.FindIndex(item => item.ID == someIDvar &&
item.OtherID == another);
在上面的代码段中,我们使用&&
运算符。 使用上面的代码片段,您将获得名为test的列表中第一个元素的索引,该元素具有特定的ID和特定的OtherID。
另一种方法是:
// Get the first element that fulfills your criteria.
test element = test.Where((item => item.ID == someIDvar &&
item.OtherID == another)
.FirstOrDefault();
// Initialize the index.
int index = -1
// If the element isn't null get it's index.
if(element!=null)
index = test.IndexOf(element)
有关更多文档,请在此处查看List.FindIndex方法(谓词) 。
从字面上看&&
(和)运算符:
int index = test.FindIndex(item => item.ID == someIDvar
&& item.OtherID == otherIDvar);
没有理由不能使谓语变得更加复杂:
int index = test.FindIndex(item => item.ID == someIDvar
&& item.OtherID == someOtherIDvar);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.