如何在 C# 中返回通用列表集合?

发布于 2024-08-15 16:55:18 字数 1653 浏览 5 评论 0原文

我有一些 linq to sql 方法,当它执行查询时,它返回一些匿名类型。

我想将该匿名类型返回到我的服务层以对其执行一些逻辑和操作。

虽然我不知道怎么退货。

我以为我可以做到这一点

public List<T> thisIsAtest()
{
     return query;
}

,但我收到此错误

Error   1   The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

所以不确定我缺少哪个程序集或者是否是这种情况。

谢谢

编辑

好的,我的第一个问题已经解决了,但现在我有一个新问题,我不知道如何解决,因为我对匿名类型不太了解。

我收到这个错误

无法隐式转换类型 '系统.集合.通用.列表' 到'System.Collections.Generic.List

这是查询

   DbContext.Table.Where(u => u.Table.UserId == userId && u.OutOFF != 0)
       .GroupBy(u => new { u.Table.Prefix })
       .Select(group => new { prefix = group.Key, 
                              Marks = group.Sum(item => (item.Mark * item.Weight) / item.OutOFF) })
       .ToList();

编辑2

public class ReturnValue
{
   string prefix { get; set; }
   decimal? Marks { get; set; } 
}

public List<ReturnValue> MyTest(Guid userId)
{
   try
   {
       var result = dbContext.Table.Where(u => u.Table.UserId == userId && u.OutOFF != 0).GroupBy(u => new { u.Table.Prefix })
       .Select(group => new { prefix = group.Key, Marks = group.Sum(item => (item.Mark * item.Weight) / item.OutOFF) }).ToList();
       return result;
   }
   catch (SqlException)
   {
       throw;
   }

选择其中包含此内容

Anonymous Types:

a is new{string Prefix}
b is new{ 'a prefix, decimal? marks}

I have some linq to sql method and when it does the query it returns some anonymous type.

I want to return that anonymous type back to my service layer to do some logic and stuff on it.

I don't know how to return it though.

I thought I could do this

public List<T> thisIsAtest()
{
     return query;
}

but I get this error

Error   1   The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

So not sure what assembly I am missing or if that is even the case.

Thanks

EDIT

Ok my first problem was solved but now I have a new problem that I am not sure how to fix since I don't know much about anonymous types.

I get this error

Cannot implicitly convert type
'System.Collections.Generic.List'
to 'System.Collections.Generic.List

Here is the query

   DbContext.Table.Where(u => u.Table.UserId == userId && u.OutOFF != 0)
       .GroupBy(u => new { u.Table.Prefix })
       .Select(group => new { prefix = group.Key, 
                              Marks = group.Sum(item => (item.Mark * item.Weight) / item.OutOFF) })
       .ToList();

Edit 2

public class ReturnValue
{
   string prefix { get; set; }
   decimal? Marks { get; set; } 
}

public List<ReturnValue> MyTest(Guid userId)
{
   try
   {
       var result = dbContext.Table.Where(u => u.Table.UserId == userId && u.OutOFF != 0).GroupBy(u => new { u.Table.Prefix })
       .Select(group => new { prefix = group.Key, Marks = group.Sum(item => (item.Mark * item.Weight) / item.OutOFF) }).ToList();
       return result;
   }
   catch (SqlException)
   {
       throw;
   }

the select has this in it

Anonymous Types:

a is new{string Prefix}
b is new{ 'a prefix, decimal? marks}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

谜泪 2024-08-22 16:55:18
public List<T> thisIsAtest<T>()
{
     return query;
}
public List<T> thisIsAtest<T>()
{
     return query;
}
開玄 2024-08-22 16:55:18

你不能——就这样。您不能在其自身范围之外使用匿名类型,例如,您不能将它们作为方法的返回值返回。

如果需要返回它们,则需要定义一个新的具体类而不是匿名类型,并使用它来代替匿名类型。

请参阅 Rick Strahl 的关于匿名类型范围的博客文章,并参阅MSDN 文档 明确指出:

匿名类型具有方法范围。到
传递一个匿名类型,或者
包含匿名的集合
类型,在方法边界之外,您
必须首先将类型转换为对象。

然而,这却打败了强者
匿名类型的输入。如果你
必须存储您的查询结果或通过
它们在方法边界之外,
考虑使用普通的命名
结构或类而不是
匿名类型。

好吧,当然——确实有一些肮脏可怕的黑客可以返回匿名类型。但如果 Microsoft 的 MSDN Jon Skeet 不鼓励这种做法,那么 - 就不要这样做。根据定义和意图,匿名类型绑定到它们定义的方法。chobo2

更新:我不知道你的数据类型是什么 - 只是猜测 - 但假设“前缀”是一个 int并且“marks”是十进制,您可以定义一个新类:

public class ReturnValue
{
    int prefix { get; set; }
    decimal Marks { get; set; } 
}  

然后您的代码将是一个返回 List 的方法:

public List<ReturnValue> thisIsAtest()
{
   DbContext.Table.Where(u => u.Table.UserId == userId && u.OutOFF != 0)
     .GroupBy(u => new { u.Table.Prefix })
     .Select(group => new ReturnValue 
                          { prefix = group.Key, 
                            Marks = group
                              .Sum(item => (item.Mark * item.Weight) / item.OutOFF) })
     .ToList();
}

这里的关键是:在您的 .Select 中 方法,而不是创建匿名类型的新实例:

     .Select(group => new { prefix = group.Key, marks = .... }

您创建一个具体类型的实例:

     .Select(group => new ReturnValue { prefix = group.Key, marks = .... }

这样,您将拥有一个具体类 ReturnValue - 命名任何你喜欢的东西 - 然后你可以轻松返回该类型的列表,并在其他地方使用该类型。

You can't - period. You cannot use anonymous types outside their own scope, e.g. you cannot return them as return values from a method.

If you need to return them, you need to define a new concrete class instead of the anonymous type, and use that in the place of the anonymous type.

See Rick Strahl's blog post on the scoping of anonymous types, and see the MSDN docs here which clearly state:

An anonymous type has method scope. To
pass an anonymous type, or a
collection that contains anonymous
types, outside a method boundary, you
must first cast the type to object.

However, this defeats the strong
typing of the anonymous type. If you
must store your query results or pass
them outside the method boundary,
consider using an ordinary named
struct or class instead of an
anonymous type.

OK, sure - there are dirty awful hacks to indeed return anonymous types. But if Microsoft's MSDN AND Jon Skeet discourage that practice, then - just don't do it. By definition and intention, anonymous types are bound to the method they're defined in.

UPDATE for chobo2: I don't know what your datatypes are - just guessing - but assuming "prefix" is an int and "marks" is a decimal, you could define a new class:

public class ReturnValue
{
    int prefix { get; set; }
    decimal Marks { get; set; } 
}  

and then your code would be a method that returns a List<ReturnValue>:

public List<ReturnValue> thisIsAtest()
{
   DbContext.Table.Where(u => u.Table.UserId == userId && u.OutOFF != 0)
     .GroupBy(u => new { u.Table.Prefix })
     .Select(group => new ReturnValue 
                          { prefix = group.Key, 
                            Marks = group
                              .Sum(item => (item.Mark * item.Weight) / item.OutOFF) })
     .ToList();
}

The key here is: in your .Select method, instead of creating a new instance of an anonymous type:

     .Select(group => new { prefix = group.Key, marks = .... }

you create an instance of a concrete type:

     .Select(group => new ReturnValue { prefix = group.Key, marks = .... }

This way, you'll have a concrete class ReturnValue - name that anything you like - and then you can easily return a list of that type, and use that type elsewhere, too.

葬花如无物 2024-08-22 16:55:18

您想从常规方法返回匿名类型吗?我很确定你可以使用反射,但不会有类型安全和一大堆其他问题。更不用说从调用代码的角度来看它看起来很奇怪。我认为你基本上必须返回对象。

您最好使用类或结构并将值填充到其中。

You want to return an anonymous type from a regular method? I'm quite sure you can with Reflection, but there would be no type safety and a whole host of other problems. Not to mention it looks weird from the calling codes perspective. You would basically have to return object I think.

You would be better use a class or struct and stuff the values in there.

思慕 2024-08-22 16:55:18

匿名类型非常有限,您只能在声明它们的方法范围内使用它们。

您可以将它们作为普通对象传递回来,但随后您会丢失类型信息。我见过一些传递匿名类型的解决方案;但他们稍后使用反射来检索属性。

Anonymous types are very limited, you can only use them in the scope of the method were they are declared.

You can pass them back as plain objects, but then you lose the type information. I have seen some solutions passing a anonymous type around; but they use reflection to retrieve the properties at a later point.

赠我空喜 2024-08-22 16:55:18

如果将通用列表声明为全局变量,则不需要使用 return。无论如何,我在代码中使用了 return 函数,只是因为 marc_s 说我不能。哈哈

 public static class Globals
    {
        public static List<string> CurPart = new List<string>();
    }
    public List<string> MSQueryRead1DArray(string sql, string db)
    {
        return Globals.CurPart;
    }

If you declare the generic list as a global variable, you don't need to use return. I used the return function in my code anyway simply because marc_s said i couldn't. lol

 public static class Globals
    {
        public static List<string> CurPart = new List<string>();
    }
    public List<string> MSQueryRead1DArray(string sql, string db)
    {
        return Globals.CurPart;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文