这段代码是什么意思? (IEnumerable <int> query = from num in list)</int>

时间:2012-08-04 11:26:42

标签: c# .net linq ienumerable

这是什么意思:

IEnumerable<int> query = from num in list
                         where num < 3
                         select num;

这是IEnumerable<T>的对象吗?

有人可以形容这个吗?

2 个答案:

答案 0 :(得分:5)

你知道正常的方法语法,对吧?像list.Add(10)这样的事情。微软的一些聪明人注意到许多集合和列表中存在相似之处。人们可能喜欢选择某些值并对可以在所有集合上运行的值进行求和,而不是每个集合都为它提供方法。

因此,他们引入了扩展方法,这些方法只定义一次,但可以应用于某种类型的所有对象,例如集合。例如list.Wherelist.Sum。要使用扩展方法,您必须add the namespace in which they are definedWhere扩展方法采用lambda表达式,该表达式在集合的每个元素上执行。

假设你有一些整数列表:

List<int> list = new List<int>();
list.Add(-1);
list.Add(0);
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);

然后,我以前必须编写以下代码才能获得小于3的整数:

List<int> query = new List<int>();
foreach(var nr in list)
{
    if (nr < 3)
        query.Add(nr);
}

现在,使用扩展方法,我可以这样写:

IEnumerable<int> query = list.Where(nr => nr < 3);

枚举时,query只返回list小于3的整数。这些扩展方法是LINQ的一部分,Language Integrated Query

然而,为了使LINQ更易于使用,他们设计了一种新的语法。使用这种新语法,LINQ更易于读写。

IEnumerable<int> query = from nr in list
                         where nr < 3
                         select nr;

编译器采用新语法并将其转换为前面提到的包含Where方法的代码。你看,它只是一种语法糖,可以更容易地处理集合。

IEnumerable<int> interface是可以枚举的任何对象的通用接口。最简单的枚举形式是对对象执行foreach,并逐个返回它包含的所有整数。因此,LINQ查询返回某个对象,但您并不确切知道该类型。但是你知道它可以枚举,这使它非常有用。

答案 1 :(得分:2)

这是一个linq等同于说

IEnumerable<int> GetLessThanThree(IEnumerable<int> list)
{
   foreach(int num in list)
   {
     if (num < 3)
     {
        yield return num
     }
   }
}

或者如果你还没有达到收益率

IEnumerable<int> GetLessThanThree(IEnumerable<int> list)
{
   List<int> result = new List<int>();
   foreach(int num in list)
   {
     if (num < 3)
     {
        result.Add(num);
     }
   }
   return result;
}