Best practice for returning IEnumerables from LINQ methods

OK

This question has probably been answered before, but I'm not sure how to spell the title.

I have a class that has methods that return many complex LINQ queries. Most of these queries form anonymous types to get the data I want. I found out that I cannot return Anonymous type from a method, so I created sub-classes and filled them in the "select new" part of the query.

Is there a better way to do this? All of these methods return IEnumerable and I really want everything to be retrieved.

Thank!

0


source to share


2 answers


You can explicitly define the anonymous types you use as classes and return those classes instead.



Generally, if you are writing a library for consumption by others, explicit classes are best practice.

+1


source


or you can use dp technique in this post



// Useful? probably not.
private void foo()
{
    var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) });
    Console.WriteLine("Name: {0} Badges: {1}", user.Name, user.Badges);
}

object GetUserTuple()
{
    return new { Name = "dp", Badges = 5 };
}    

// Using the magic of Type Inference...
static T AnonCast<T>(object obj, T type)
{
   return (T) obj;
}

      

0


source







All Articles