views:

425

answers:

1

I'm in a little bit of a road block here, but what I would like to ultimately do is to create a recordset based off of a query and store the information into separate objects (let's call them Foo) then create a new query to group all the Foo objects with the same id's into an ArrayList into Bar objects. How would I go about doing this in 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

So, in the end I should have a recordset of Bar objects with a list of Foo objects.

+1  A: 

It's kind of hard to tell if you want 1 Bar or several Bars, but here's my best stab with the information provided.

Supposing you had:

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

Then you could do:

//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();
David B
this properly creates foo objects and stores them into bar objects but the algorithm to group all the same ids from the first query together in a list doesnt work
Ayo
Doesn't work, how? I've used this technique many times.
David B