[英]How to return an object (or a list of objects) of anonymous type from a LINQ query to the UI (Console App) in C#?
Let us say I query multiple tables with LINQ using joins and groupbys, resulting in an IQueryable<'a>
of anonymous objects which I want to pass to the UI layer. 假设我使用join和groupbys使用LINQ查询多个表,结果是我想传递给UI层的匿名对象的IQueryable<'a>
。 How do I manage that? 我该如何处理?
I can return the IQueryable<'a>
(IQueryable of an anonymous type), if the return type of the method is the simple non-generic IQueryable
. 如果方法的返回类型是简单的非泛型IQueryable
,则可以返回IQueryable<'a>
(匿名类型的IQueryable
。 But how do I use this non-generic IQueryable
object, how can I access the properties of the contained anonymous objects? 但是,如何使用此非通用IQueryable
对象,如何访问包含的匿名对象的属性?
You can't do that. 你不能那样做。 You will need to create a DTO for that which will have the required properties. 您将需要为其创建具有所需属性的DTO。
public class DTO
{
public int PropA { get; set; }
.......
.......
}
and then materialize your query in to the DTO : 然后将您的查询具体化到DTO中:
public List<DTO> GetData()
{
return query.Select(x= > new DTO()
{
PropA = x.SomeColumn,
...........
...........
}).ToList();
}
Hope it helps. 希望能帮助到你。
You could make use of value tuples, so return a new value tuple like this: 您可以使用值元组,因此返回一个新的值元组,如下所示:
public (string Name, int Age, DateTimeOffset Timestamp)[] GetValues()
{
return database.Where(x => ...)
.Select(x => (Name: x.Name, Age: x.Age, Timestamp: DateTimeOffset.Now))
.ToArray();
}
Then you get a generic array with value tuples as result, and can access those values using the given property names, for example like this: 然后,您将获得一个以值元组为结果的通用数组,并可以使用给定的属性名称访问这些值,例如:
var array = GetValues();
var age = array.First(x => x.Name == "John Doe").Age;
That way you get the flexibility of not having to define a custom type 这样,您不必定义自定义类型即可获得灵活性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.