Just a little niggle about LINQ syntax. I’m flattening an IEnumerable<IEnumerable<T>> with SelectMany(x => x).
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)?
Note: this answer was correct for C# 3, but at some point (C# 4? C# 5?) type inference improved so that the
IdentityFunctionmethod shown below can be used easily.No, there isn’t. It would have to be generic, to start with:
But then type inference wouldn’t work, so you’d have to do:
which is a lot uglier than
x => x.Another possibility is that you wrap this in an extension method:
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:But again, you’ve then got type inference problems, I suspect…
EDIT: To respond to the comments… yes, C# 4 makes this easier. Or rather, it makes the first
Flattenmethod 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 fromList<List<string>>toIEnumerable<IEnumerable<string>>: