简体   繁体   中英

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. 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 . But how do I use this non-generic IQueryable object, how can I access the properties of the contained anonymous objects?

You can't do that. You will need to create a DTO for that which will have the required properties.

public class DTO
{
    public int PropA { get; set; }
    .......
    .......
}

and then materialize your query in to the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM