Return anonymous type results?

后端 未结 16 1423
梦毁少年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:51

    No you cannot return anonymous types without going through some trickery.

    If you were not using C#, what you would be looking for (returning multiple data without a concrete type) is called a Tuple.

    There are alot of C# tuple implementations, using the one shown here, your code would work like this.

    public IEnumerable> GetDogsWithBreedNames()
    {
        var db = new DogDataContext(ConnectString);
        var result = from d in db.Dogs
                     join b in db.Breeds on d.BreedId equals b.BreedId
                     select new Tuple(d, b);
    
        return result;
    }
    

    And on the calling site:

    void main() {
        IEnumerable> dogs = GetDogsWithBreedNames();
        foreach(Tuple tdog in dogs)
        {
            Console.WriteLine("Dog {0} {1}", tdog.param1.Name, tdog.param2.BreedName);
        }
    }
    

提交回复
热议问题