我的Lambda表达有什么不对?

时间:2012-02-21 15:31:54

标签: c# .net list lambda

我正在尝试用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表达式的理解以及它们的工作方式仍然有点阴暗,我对于为什么这不起作用我很恼火......我试图找出一个列表是否包含一个名字......

7 个答案:

答案 0 :(得分:7)

您在寻找:

bool test = people.Any(p => p.FirstName == "Bob");

或者你在混合Rob和Bob?

答案 1 :(得分:6)

这里的问题不是lambdas,而是for循环的边界。您定义的数组的长度为3,但numElements的定义值为10。这意味着在循环的第4次迭代中,您将获得非法数组索引的异常。请尝试以下

int numElements = 3;

或者更简单地删除numElements变量,而是迭代到firstnames数组的长度

for (int i = 0; i < firstnames.length; i++) {
  ...
}

编辑

OP表示最初发布的numElements是一个拼写错误。代码中其他可能的错误来源

  • 如果要查找匹配元素,请使用"Rob"代替"Bob"
  • Contains上的GenericList<T>方法需要具有兼容的委托签名。例如Func<T, bool>

答案 2 :(得分:3)

  1. 确保链接System.Linq名称空间,即

    using System.Linq;
    
  2. 您正在使用Contains方法。此方法需要Person,并将使用相等比较来确定您的集合是否已包含它。在默认情况下,相等比较默认为引用比较,因此它永远不会包含它,但这是另一个主题。

  3. 要实现目标,请使用Any方法。这将告诉您集合中的任何元素是否符合条件。

    people.Any(p => p.FirstName == "BoB");
    
  4. 您可能想了解the extension methods First和FirstOrDefault以及它们也可以解决您的问题。

答案 3 :(得分:2)

您没有将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");

答案 4 :(得分:0)

这个lambdas你真正的问题是什么?

如果因为你的测试是假的那么这是真的你在firstName中没有“Bob”

bool test = people.Contains(p => p.FirstName == "Bob");

string[]firstnames = {"Dave", "Jim", "Rob"};

答案 5 :(得分:0)

这里有几个问题。

一:GenericList不是一种类型。您可能正在寻找通用类型System.Collections.Generic.List<T>

二:Contains在您的示例中接受Person,而不是委托(lambda是从C#3开始编写委托的新方法)。获取您想要的内容的一种方法是以Where

的形式合并Countbool test = people.Where(p => p.FirstName == "Bob").Count() > 0;

答案 6 :(得分: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方法一段时间......