Return anonymous type results?

后端 未结 16 1118
梦毁少年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<Tuple<Dog,Breed>> 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<Dog,Breed>(d, b);
    
        return result;
    }
    

    And on the calling site:

    void main() {
        IEnumerable<Tuple<Dog,Breed>> dogs = GetDogsWithBreedNames();
        foreach(Tuple<Dog,Breed> tdog in dogs)
        {
            Console.WriteLine("Dog {0} {1}", tdog.param1.Name, tdog.param2.BreedName);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:56

    Try this to get dynamic data. You can convert code for List<>

    public object 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
                            {
                                Name = d.Name,
                                BreedName = b.BreedName
                            };
        return result.FirstOrDefault();
    }
    
    dynamic dogInfo=GetDogsWithBreedNames();
    var name = dogInfo.GetType().GetProperty("Name").GetValue(dogInfo, null);
    var breedName = dogInfo.GetType().GetProperty("BreedName").GetValue(dogInfo, null);
    
    0 讨论(0)
  • 2020-11-22 04:01

    You must use ToList() method first to take rows from database and then select items as a class. Try this:

    public partial class Dog {
        public string BreedName  { get; set; }}
    
    List<Dog> 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
                      {
                          Name = d.Name,
                          BreedName = b.BreedName
                      }).ToList()
                        .Select(x=> 
                              new Dog{
                                  Name = x.Name,
                                  BreedName = x.BreedName,
                              }).ToList();
    return result;}
    

    So, the trick is first ToList(). It is immediately makes the query and gets the data from database. Second trick is Selecting items and using object initializer to generate new objects with items loaded.

    Hope this helps.

    0 讨论(0)
  • 2020-11-22 04:02

    Just to add my two cents' worth :-) I recently learned a way of handling anonymous objects. It can only be used when targeting the .NET 4 framework and that only when adding a reference to System.Web.dll but then it's quite simple:

    ...
    using System.Web.Routing;
    ...
    
    class Program
    {
        static void Main(string[] args)
        {
    
            object anonymous = CallMethodThatReturnsObjectOfAnonymousType();
            //WHAT DO I DO WITH THIS?
            //I know! I'll use a RouteValueDictionary from System.Web.dll
            RouteValueDictionary rvd = new RouteValueDictionary(anonymous);
            Console.WriteLine("Hello, my name is {0} and I am a {1}", rvd["Name"], rvd["Occupation"]);
        }
    
        private static object CallMethodThatReturnsObjectOfAnonymousType()
        {
            return new { Id = 1, Name = "Peter Perhac", Occupation = "Software Developer" };
        }
    }
    

    In order to be able to add a reference to System.Web.dll you'll have to follow rushonerok's advice : Make sure your [project's] target framework is ".NET Framework 4" not ".NET Framework 4 Client Profile".

    0 讨论(0)
提交回复
热议问题