2009-06-03 5 views
0

여기로드 블록에 약간 있지만, 궁극적으로 할 일은 쿼리를 기반으로 레코드 집합을 만들고 별도의 정보를 저장하는 것입니다. 객체 (Foo라고 부름)를 호출 한 다음 동일한 id를 가진 모든 Foo 객체를 ArrayList에 그룹화하여 Bar 객체로 그룹화하는 새 쿼리를 만듭니다. Linq에서 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 

그래서 결국에는 Foo 개체 목록이있는 Bar 개체의 레코드 집합이 있어야합니다.

+0

있습니까? – cdonner

+0

및 IQueryable에 색을 쿼리하려면 Foo 클래스에 색을 추가해야합니다. – cdonner

+0

arrayList에 대한 이유는 각 막대에 둘 이상의 foo가 있다는 것입니다. – Ayo

답변

1

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;} 
} 

그런 다음 당신은 할 수 있습니다 : 당신이 ArrayList를 원하는 왜 특별한 이유가

//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(); 
+0

이것은 foo 객체를 적절하게 생성하여 막대 객체에 저장하지만 목록의 첫 번째 쿼리와 동일한 ID를 모두 그룹화하는 알고리즘은 작동하지 않습니다. – Ayo

+0

어떻게 작동하지 않습니까? 나는이 기술을 여러 번 사용했습니다. –