从现有的查询中查询记录集Linq To Sql

问题描述:

我在这里有一点路障,但我最终想做的是根据查询创建一个记录集并将信息存储到单独的对象(让我们称它们为Foo),然后创建一个新的查询,将具有相同ID的所有Foo对象分组成一个ArrayList到Bar对象中。我如何去Linq to SQL做这件事?从现有的查询中查询记录集Linq To Sql

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 

那么,到底我应该有吧对象的记录与富贵对象的列表。

+0

为什么你想一个ArrayList有什么特别的原因? – cdonner 2009-06-03 17:54:15

+0

,如果你想查询你的IQueryable的颜色,你将不得不添加颜色到你的Foo类。 – cdonner 2009-06-03 17:55:09

这是很难分辨,如果你想1酒吧或几个酒吧,但这是我提供的信息最好的刺。

假设你有:

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();