LINQ身份的功能? [英] LINQ identity function?
问题描述
刚想LINQ语法有点挑剔。我压扁了的IEnumerable< IEnumerable的< T>>
与的SelectMany(X => X)。
Just a little niggle about LINQ syntax. I'm flattening an IEnumerable<IEnumerable<T>>
with SelectMany(x => x)
.
我的问题是lambda表达式 X => X
。它看起来有点丑。有一些静态的身份功能的对象,我可以改用的X => X
? ?像的SelectMany(IdentityFunction)
My problem is with the lambda expression x => x
. It looks a bit ugly. Is there some static 'identity function' object that I can use instead of x => x
? Something like SelectMany(IdentityFunction)
?
推荐答案
请注意:这个答案是正确的C#3,但在某些时候(C#4?C#5?)类型推断改进,使下图所示的 IdentityFunction
方法的可以的使用容易。
Note: this answer was correct for C# 3, but at some point (C# 4? C# 5?) type inference improved so that the IdentityFunction
method shown below can be used easily.
没有,没有。它必须是通用的,先从:
No, there isn't. It would have to be generic, to start with:
public static Func<T, T> IdentityFunction<T>()
{
return x => x;
}
但随后类型推断是行不通的,所以你必须做
But then type inference wouldn't work, so you'd have to do:
SelectMany(Helpers.IdentityFunction<Foo>())
比 X =>难看很多; 。X
另一种可能是您在扩展方法包装这样的:
Another possibility is that you wrap this in an extension method:
public static IEnumerable<T> Flatten<T>
(this IEnumerable<IEnumerable<T>> source)
{
return source.SelectMany(x => x);
}
不幸的是与一般的方差事情是这样的,那可能落入各种犯规例如:;在C#3个案...这将不适用列表<名单,LT;串GT;>。你可以使它更通用的:
Unfortunately with generic variance the way it is, that may well fall foul of various cases in C# 3... it wouldn't be applicable to List<List<string>>
for example. You could make it more generic:
public static IEnumerable<TElement> Flatten<TElement, TWrapper>
(this IEnumerable<TWrapper> source) where TWrapper : IEnumerable<TElement>
{
return source.SelectMany(x => x);
}
但同样,你便起身类型推断的问题,我怀疑...
But again, you've then got type inference problems, I suspect...
编辑:为了应对的意见......是的,C#4使这更容易。或者说,它使第一个平展
办法比它是在C#3.下面是这在C#4工作的示例比较有用,但不工作在C#3,因为编译器不能从列表与LT转换;列表<串>>
到的IEnumerable< IEnumerable的<串>>
:
To respond to the comments... yes, C# 4 makes this easier. Or rather, it makes the first Flatten
method more useful than it is in C# 3. Here's an example which works in C# 4, but doesn't work in C# 3 because the compiler can't convert from List<List<string>>
to IEnumerable<IEnumerable<string>>
:
using System;
using System.Collections.Generic;
using System.Linq;
public static class Extensions
{
public static IEnumerable<T> Flatten<T>
(this IEnumerable<IEnumerable<T>> source)
{
return source.SelectMany(x => x);
}
}
class Test
{
static void Main()
{
List<List<string>> strings = new List<List<string>>
{
new List<string> { "x", "y", "z" },
new List<string> { "0", "1", "2" }
};
foreach (string x in strings.Flatten())
{
Console.WriteLine(x);
}
}
}
这篇关于LINQ身份的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!