从LINQ方法返回IEnumerables的最佳实践

时间:2021-02-02 21:18:40

OK,

This question has probably been answered before, but I'm not sure of how to word the Title.

这个问题之前可能已经得到了回答,但我不确定如何标题。

I have a class that has methods which return many composite LINQ queries. Most of these queries form Anonymous Types in order to get the data I need. I found out that I'm not able to return an Anonymous Type from a method, so I've been creating sub classes and populating them in the "select new" part of the query.

我有一个类,它有返回许多复合LINQ查询的方法。大多数这些查询形成匿名类型以获取我需要的数据。我发现我无法从方法中返回Anonymous Type,所以我一直在创建子类并在查询的“select new”部分填充它们。

Is there a better way of doing this? All of these methods return an IEnumerable of some kind and I really want to keep things extracted.

有更好的方法吗?所有这些方法都返回了某种类型的IEnumerable,我真的想保留一些东西。

Thanks!

2 个解决方案

#1


1  

You could explictly define the anonymous types you are using as classes, and instead return those classes.

您可以明确地定义您作为类使用的匿名类型,而是返回这些类。

Generally if you are writing a library for others to consume, explicitly defined classes are a best practice.

通常,如果您正在编写供其他人使用的库,则明确定义的类是最佳实践。

#2


0  

or you can use technic of dp in this post

或者你可以在这篇文章中使用dp的技术

// 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;
}

#1


1  

You could explictly define the anonymous types you are using as classes, and instead return those classes.

您可以明确地定义您作为类使用的匿名类型,而是返回这些类。

Generally if you are writing a library for others to consume, explicitly defined classes are a best practice.

通常,如果您正在编写供其他人使用的库,则明确定义的类是最佳实践。

#2


0  

or you can use technic of dp in this post

或者你可以在这篇文章中使用dp的技术

// 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;
}