简介C#列表理解 [英] Introduction to C# list comprehensions

查看:127
本文介绍了简介C#列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在C#中执行列表理解?

How can I perform list comprehensions in C#?

推荐答案

一个列表理解是一种集表示法中,程序员可以描述一组的成员必须满足的属性。它通常用于通过施加某些类型的组合的基于其他,已经存在的设置或设置来创建一组,变换或缩小功能到现有的组(多个)。

A List Comprehension is a type of set notation in which the programmer can describe the properties that the members of a set must meet. It is usually used to create a set based on other, already existing, set or sets by applying some type of combination, transform or reduction function to the existing set(s).

考虑以下问题:您有10个数字从0到9的顺序,你需要提取所有甚至从该序列号。在语言这样一个C#1.1版,你非常局限于下面的代码来解决这个问题:

Consider the following problem: You have a sequence of 10 numbers from 0 to 9 and you need to extract all the even numbers from that sequence. In a language such a C# version 1.1, you were pretty much confined to the following code to solve this problem:

ArrayList evens = new ArrayList();
ArrayList numbers = Range(10);
int size = numbers.Count;
int i = 0;

while (i < size) 
{
    if (i % 2 == 0) 
    {
        evens.Add(i);
    }
    i++;
}



上面的代码并不显示范围功能的实现,这是可以在完整的代码下面的清单。随着C#3.0的问世和.NET Framework 3.5,基于Linq的列表理解表示法现在可以到C#程序员。上述C#1.1的代码可以移植到C#3.0,像这样:

The code above does not show the implementation of the Range function, which is available in the full code listing below. With the advent of C# 3.0 and the .NET Framework 3.5, a List Comprehension notation based on Linq is now available to C# programmers. The above C# 1.1 code can be ported to C# 3.0 like so:

IEnumerable<int> numbers = Enumerable.Range(0, 10);
var evens = from num in numbers where num % 2 == 0 select num;

和技术上来说,在C#3.0上面的代码可以通过移动电话可以写成一个班轮到的 Enumarable.Range 的到生成的找齐的序列中的LINQ表达式。在C#列表理解我减少集的数字的通过应用功能(模2)该序列。这就产生了一个更简洁的方式的找齐的序列,并避免使用循环语法。现在,你可能会问自己:这是纯粹的语法糖吗?我不知道,但我会definitelly调查,甚至可能在这里问这个问题我自己。我怀疑这是不是只是语法糖,而且有可以利用底层的单子做一些真正的优化。

And technically speaking, the C# 3.0 code above could be written as a one-liner by moving the call to Enumarable.Range to the Linq expression that generates the evens sequence. In the C# List Comprehension I am reducing the set numbers by applying a function (the modulo 2) to that sequence. This produces the evens sequence in a much more concise manner and avoid the use of loop syntax. Now, you may ask yourself: Is this purely syntax sugar? I don't know, but I will definitelly investigate, and maybe even ask the question myself here. I suspect that this is not just syntax sugar and that there are some true optimizations that can be done by utilizing the underlying monads.

的完整代码列表可用的这里

The full code listing is available here.

这篇关于简介C#列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆