如何在 C# 中返回通用列表集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1937301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return a generic list collection in C#?
提问by chobo2
I have some linq to sql method and when it does the query it returns some anonymous type.
我有一些 linq to sql 方法,当它执行查询时,它返回一些匿名类型。
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
无法将类型“System.Collections.Generic.List”隐式转换为“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
编辑 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}
采纳答案by marc_s
You can't - period. You cannotuse 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 poston the scoping of anonymous types, and see the MSDN docs herewhich clearly state:
请参阅 Rick Strahl关于匿名类型范围的博客文章,并在此处查看MSDN 文档,其中明确说明:
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 ANDJon 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.
好的,当然 - 有肮脏可怕的黑客确实返回匿名类型。但是,如果 Microsoft 的 MSDN和Jon Skeet 不鼓励这种做法,那就不要这样做。根据定义和意图,匿名类型绑定到它们定义的方法。
UPDATEfor 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:
chobo2更新:我不知道你的数据类型是什么——只是猜测——但假设“前缀”是一个整数,“标记”是一个小数,你可以定义一个新类:
public class ReturnValue
{
int prefix { get; set; }
decimal Marks { get; set; }
}
and then your code would be a method that returns a List<ReturnValue>
:
然后你的代码将是一个返回一个的方法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
方法中,而不是创建一个匿名类型的新实例:
.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.
通过这种方式,您将拥有一个具体的类ReturnValue
- 以您喜欢的任何名称命名 - 然后您可以轻松返回该类型的列表,并在其他地方也使用该类型。
回答by Yuriy Faktorovich
public List<T> thisIsAtest<T>()
{
return query;
}
回答by Skurmedel
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.
您想从常规方法返回匿名类型吗?我很确定你可以使用 Reflection,但不会有类型安全和一大堆其他问题。更不用说从调用代码的角度来看它看起来很奇怪。我认为您基本上必须返回对象。
You would be better use a class or struct and stuff the values in there.
您最好使用类或结构并将值填充在其中。
回答by driis
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.
您可以将它们作为普通对象传回,但是您会丢失类型信息。我见过一些传递匿名类型的解决方案;但他们稍后使用反射来检索属性。