Significance of AsEnumerable?
-
05-02-2021 - |
Question
var query =
from dt1 in dtStudent.AsEnumerable()
join dt2 in dtMarks.AsEnumerable()
on dt1.Field<int>("StudentID")
equals dt2.Field<int>("StudentID")
select new StudentMark
{
StudentName = dt1.Field<string>("StudentName"),
Mark = dt2.Field<int>("Mark")
};
In the above coding, what is the significance of AsEnumerable
? if the AsEnumerable
doesn't exist in .NET Framework, then what would be the approach of developers to perform the above the task?
La solution
Assuming I'm interpreting it correctly, it's calling DataTableExtensions.AsEnumerable()
. Without that (or something similar), you can't use LINQ to Objects as DataTable
doesn't implement IEnumerable<T>
, only IEnumerable
.
Note that an alternative would be to use Cast<DataRow>
, but that would be subtly different as that would use the DataTable
's GetEnumerator
directly within Cast
, whereas I believe EnumerableRowCollection<TRow>
does slightly more funky things with the data table. It's unlikely to show up any real changes, except possibly a slight performance difference.
Autres conseils
The .AsEnumerable()
extension is just short-hand for casting something that implements IEnumerable<T>
to be IEnumerable<T>
So, if xs
is int[]
, you can call xs.AsEnumerable()
instead of (xs as IEnumerable<int>)
. It uses type inference to avoid needing to explicitly keying the type of xs
.
Here's the code extracted by Reflector.NET:
public static IEnumerable<TSource> AsEnumerable<TSource>(
this IEnumerable<TSource> source)
{
return source;
}
But in this case I think I have to agree with Jon. It's probably from the System.Data.DataSetExtensions
assembly.