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?

Was it helpful?

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top