开发者

Significance of AsEnumerable?

开发者 https://www.devze.com 2023-04-09 12:18 出处:网络
var query = from dt1 in dtStudent.AsEnumerable() join dt2 in dtMarks.AsEnumerable() on dt1.Field<int>(\"StudentID\")
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&l开发者_如何学JAVAt;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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号