[英]What's Wrong With My Lambda Expression?
我正在尝试在C#中编写一个简单的Lambda表达式:
int numElements = 3;
string[]firstnames = {"Dave", "Jim", "Rob"};
string[]lastnames = {"Davidson", "Jameson", "Robertson"};
List<Person> people = new List<Person>();
for(int i = 0 ; i < numElements; i++)
{
people.Add(new Person { FirstName = firstnames[i], LastName = lastnames[i] });
}
bool test = people.Contains(p => p.FirstName == "Bob");
我对Lambda表达式及其工作方式的理解还有些阴暗,我想知道为什么它不起作用...我试图找出列表中是否包含名称...
您是否在寻找:
bool test = people.Any(p => p.FirstName == "Bob");
还是您要混合Rob和Bob?
这里的问题不是lambda,而是for
循环的边界。 您定义的数组的长度为3,但是numElements
的值定义为10
。 这意味着您将在循环的第4次迭代中获得非法数组索引的异常。 尝试以下
int numElements = 3;
或更简单地删除numElements
变量,而是迭代到firstnames
数组的长度
for (int i = 0; i < firstnames.length; i++) {
...
}
编辑
OP表示最初发布的numElements
是一个错字。 代码中其他可能的错误源
"Rob"
而不是"Bob"
GenericList<T>
上的Contains
方法需要具有兼容的委托签名。 Func<T, bool>
确保您链接了System.Linq名称空间,即
using System.Linq;
您正在使用Contains方法。 此方法需要一个Person并将使用相等比较来确定您的集合是否已包含它。 在默认情况下,相等比较默认为引用比较,因此它永远不会包含引用比较,但这是另一个主题。
为了实现您的目标,请使用Any方法。 这将告诉您集合中的任何元素是否符合条件。
people.Any(p => p.FirstName == "BoB");
您可能需要阅读有关扩展方法 First和FirstOrDefault的信息,以及它们在哪里也可以解决您的问题的信息。
您没有将numElements
设置为正确的值(将其设置为10,但是您的数组只有3个值)-此外,您甚至不需要它,只需使用集合初始值设定项而不是这些单独的字符串数组即可:
GenericList<Person> people = new GenericList<Person>()
{
new Person { FirstName = "Dave", LastName = "Davidson" },
new Person { FirstName = "Jim", LastName = "Jameson" }
new Person { FirstName = "Rob", LastName = "Robertson" }
}
现在,假设您的GenericList<T>
类实现IEnumerable<T>
,则可以使用Any()
进行测试:
bool test = people.Any(p => p.FirstName == "Bob");
您对此lambda的真正问题是什么?
如果因为测试错误而成立,那么您的名字中没有“鲍勃”
bool test = people.Contains(p => p.FirstName == "Bob");
和
string[]firstnames = {"Dave", "Jim", "Rob"};
这里有几个问题。
一个: GenericList
不是类型。 您可能正在寻找通用类型System.Collections.Generic.List<T>
。
二:在您的示例中, Contains
接受一个Person
,而不是一个委托(lambda是从C#3开始编写委托的一种新方法)。 一种获得所需结果的方法是将Where
和Count
结合起来,以bool test = people.Where(p => p.FirstName == "Bob").Count() > 0;
// We will use these things:
Predicate<Person> yourPredicate = p => p.FirstName == "Bob";
Func<Person, bool> yourPredicateFunction = p => p.FirstName == "Bob";
Person specificPerson = people[0];
// Checking existence of someone:
bool test = people.Contains(specificPerson);
bool anyBobExistsHere = people.Exists(yourPredicate);
// Accessing to a person/people:
IEnumerable<Person> allBobs = people.Where(yourPredicateFunction);
Person firstBob = people.Find(yourPredicate);
Person lastBob = people.FindLast(yourPredicate);
// Finding index of a person
int indexOfFirstBob = people.FindIndex(yourPredicate);
int indexOfLastBob = people.FindLastIndex(yourPredicate);
您应该在一段时间内使用LINQ方法...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.