Return anonymous type results?

后端 未结 16 1419
梦毁少年i
梦毁少年i 2020-11-22 03:01

Using the simple example below, what is the best way to return results from multiple tables using Linq to SQL?

Say I have two tables:

Dogs:   Name, A         


        
16条回答
  •  粉色の甜心
    2020-11-22 03:42

    You can not return anonymous types directly, but you can loop them through your generic method. So do most of LINQ extension methods. There is no magic in there, while it looks like it they would return anonymous types. If parameter is anonymous result can also be anonymous.

    var result = Repeat(new { Name = "Foo Bar", Age = 100 }, 10);
    
    private static IEnumerable Repeat(TResult element, int count)
    {
        for(int i=0; i

    Below an example based on code from original question:

    var result = GetDogsWithBreedNames((Name, BreedName) => new {Name, BreedName });
    
    
    public static IQueryable GetDogsWithBreedNames(Func creator)
    {
        var db = new DogDataContext(ConnectString);
        var result = from d in db.Dogs
                        join b in db.Breeds on d.BreedId equals b.BreedId
                        select creator(d.Name, b.BreedName);
        return result;
    }
    

提交回复
热议问题