2

Say I have a list, List<Foo> SomeList, and Foo is a class that has two properties, Bar and Baz.

Is there a LINQ query that will allow me to select all the items of type Foo that share the same value for Bar, so they can be processed together?

Something like:

foreach (List<Foo> foos in SomeList.SelectBy (x => x.Bar))
{
// process foos
}

so that all the Foo items with Bar = 0 are processed first, then those with Bar set to 1, and so on and so forth.

Can this be done easily, or do I need to write that functionality myself?

MKII
  • 892
  • 11
  • 36

2 Answers2

3

That you need is to group by first and then order by the key the items in your list.

var grouped = SomeList.GroupBy(item => item.Bar)
                      .OrderBy(gr=>gr.Key);


foreach (var item in grouped)
{
    // item has a Key property associated with the value of Bar
    // You can take the list of Foo by simply calling this
    // item.ToList() and then you can process this.
}
Christos
  • 53,228
  • 8
  • 76
  • 108
0

Your question is not clear enough, so that i go for a wild guess. hope that you are looking for something like the following:

 List<Foo> SomeList = new List<Foo>();
        SomeList.Add(new Foo() {Bar=1,Baz ="ASDASD"}); 
        SomeList.Add(new Foo() {Bar=2,Baz ="dqwe"});
        SomeList.Add(new Foo() { Bar = 5, Baz = "fsdfsgsdg" });
        SomeList.Add(new Foo() { Bar = 5, Baz = "dghjhljkl" }); 
      foreach(Foo f in  SomeList.Where(x=>x.Bar==5).ToList())
      {
      // do some operations
      }

It allows you to select all the items of type Foo that share the same value for Bar(here it is 5, make it dynamic if needed)

As per Christos's suggestion you can apply OrderBy if the order is important.