代码之家  ›  专栏  ›  技术社区  ›  Ayo

从现有查询Linq到SQL查询记录集

  •  0
  • Ayo  · 技术社区  · 16 年前

    我在这里有点困难,但我最终想做的是基于查询创建一个记录集,并将信息存储到单独的对象中(我们称之为foo),然后创建一个新的查询,将所有具有相同ID的foo对象分组到一个数组列表中,再组合成bar对象。在LinqToSQL中,我该怎么做呢?

    public class Foo{
        public int id{get;set;}
        public string name{get;set;}
    }
    
    public class Bar{
        public ArrayList foos{get;set;}
    }
    
    var query = from tFoo in fooTable join tFoo2 in fooTable2 on tFoo.id equals tFoo2.id
                where tFoo2.colour = 'white'
                select new Foo
                {
                     id = tFoo.idFoo,
                     name = tFoo.name
                };
    
    var query2 = //iterate the first query and find all Foo objects with the the same
                 //tFoo.idFoo and store them into Bar objects
    

    所以,最后我应该有一个带有foo对象列表的bar对象记录集。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Amy B    16 年前

    很难判断你是想要一个酒吧还是几个酒吧,但这里是我提供的最好的信息。

    假设你有:

    public class Foo
    {
      public int id {get;set;}
      public string name {get;set;}
      public string colour {get;set;}
    }
    
    public class Bar
    {
      public int id {get;set;}
      public List<Foo> Foos {get;set;}
    }
    

    然后你可以做:

    //executes the query and pulls the results into memory
    List<Foo> aBunchOfFoos =
    (
      from foo in db.Foos
      where foo.colour == "white"
      select foo
    ).ToList();
    
    // query those objects and produce another structure.
    //  no database involvement
    List<Bar> aBunchOfBars =  aBunchOfFoos
      .GroupBy(foo => foo.id)
      .Select(g => new Bar(){id = g.Key, Foos = g.ToList() })
      .ToList();