何时何地使用LINQ到对象?对象、LINQ

2023-09-03 07:20:53 作者:伸手在风里

在哪些情况下我应该使用LINQ到对象?

In which situations I should use LINQ to Objects?

很显然,我所能做的一切,而不LINQ。因此,在操作LINQ实际上帮助我code 短和/或更可读

Obviously I can do everything without LINQ. So in which operations LINQ actually helps me to code shorter and/or more readable?

本引发这个问题的

This question triggered by this

推荐答案

我觉得LINQ到对象得到处都是有用的。它解决的问题是pretty的一般:

I find LINQ to Objects useful all over the place. The problem it solves is pretty general:

您有一些数据项的集合 您想另外一个集合,从原来的集合形成的,而是某种改造或过滤后。这可能是排序,投影,应用predicate,分组等。

这是一个情况我遇到pretty的频繁。有非常多的编程领域,基本上涉及到改变一个集合(或数据流)到另一个。在这种情况下c。使用LINQ的$ C $几乎总是短,更具可读性。我想指出的是,LINQ不应该被视为等同于查询EX pressions - 如果只需要一个单一的运营商,正常的点号(使用扩展方法)往往可以更短,更具可读性。

That's a situation I come across pretty often. There are an awful lot of areas of programming which basically involve transforming one collection (or stream of data) into another. In those cases the code using LINQ is almost always shorter and more readable. I'd like to point out that LINQ shouldn't be regarded as being synonymous with query expressions - if only a single operator is required, the normal "dot notation" (using extension methods) can often be shorter and more readable.

其中一个原因,我特别喜欢的LINQ to Objects是它的是的太笼统 - 而LINQ to SQL是可能只涉足数据层(或pretty的多少成为数据层),LINQ到对象是适用于每一个层,并在所有类型的应用程序。

One of the reasons I particularly like LINQ to Objects is that it is so general - whereas LINQ to SQL is likely to only get involved in your data layer (or pretty much become the data layer), LINQ to Objects is applicable in every layer, and in all kinds of applications.

只是作为一个例子,这里是我的MiniBench基准框架一条线,转换的TestSuite (这基本上是测试的命名集合)成 ResultSuite (结果的命名集合):

Just as an example, here's a line in my MiniBench benchmarking framework, converting a TestSuite (which is basically a named collection of tests) into a ResultSuite (a named collection of results):

return new ResultSuite(name, 
    tests.Select(test => test.Run(input, expectedOutput)));

话又说回来,如果 ResultSuite 需要对一些特定的标准的结果进行调整:

Then again if a ResultSuite needs to be scaled against some particular "standard" result:

return new ResultSuite(name, 
    results.Select(x => x.ScaleToStandard(standard, mode)));

这不会是的硬盘的写没有LINQ此code,但LINQ只是使它更清晰,让你集中精力,而不是通过循环迭代的细节上真正的逻辑并加入结果​​列表等。

It wouldn't be hard to write this code without LINQ, but LINQ just makes it clearer and lets you concentrate on the real "logic" instead of the details of iterating through loops and adding results to lists etc.

即使LINQ本身是不适用的,有些这在很大程度上包括为求LINQ(如隐式类型的局部变量,拉姆达EX pressions,扩展方法)的功能是非常有用的。

Even when LINQ itself isn't applicable, some of the features which were largely included for the sake of LINQ (e.g. implicitly typed local variables, lambda expressions, extension methods) can be very useful.