Can the data type for a generic List<T> be implied?
Is there an implicit way to tell a generic collection to use the Type
of the incoming IEnumerable<T>
data?
A开发者_Go百科ssume any Type can be incoming because it might have been obscured, for example, through IQueryable and might contain an anonymous Type.
var enumerableThings = //... enumerable<T> obtained from somewhere.
The point is T is unknown.
I want to create a List<T>
of the primary Type of the enumerable thing:
var listOfThoseThings = new List<???>(enumerableThings);
There are many interesting mechanisms in C#/.NET. I wouldn't be surprised to find the ability to carry out this task; however at the moment a concise way evades me.
This is why the ToList()
extension method exists.
var listOfThoseThings = enumerableThings.ToList();
Unlike the List<T>
constructor, it can use type inference to implcitly specify the generic parameter.
Just to expand on SLaks' (correct) answer.
When you call ToList
, that's calling the generic method Enumerable.ToList<T>(IEnumerable<T> source)
. The compiler then uses generic type inference in the normal way to work out T
.
Note that at the moment although there are calls for ToList
, ToDictionary
and ToArray
, there's no equivalent for HashSet
. It's very easy to write though:
public static class MoreExtensions
{
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
return new HashSet<T>(source);
}
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source,
IEqualityComparer<T> comparer)
{
return new HashSet<T>(source, comparer);
}
}
Doing this sort of thing is the only way of constructing an instance of a generic type with a type argument which is an anonymous type, short of generics. It's a good job it's easy :)
There is no way to directly do this however it can be indirectly done via method type inference
public static List<T> CreateList<T>(IEnumerable<T> enumerableThings)
{
return new List<T>(enumerableThings);
}
var listOfThoseThings = CreateList(enumerableThings);
static List<T> GetList<T>(IEnumerable<T> enumerableThings)
{
var listOfThoseThings = new List<T>(enumerableThings);
return listOfThoseThings;
}
精彩评论