开发者

Classify elements from a list to another classification

开发者 https://www.devze.com 2023-03-26 17:23 出处:网络
I\'\'ve got a List<Foo>. Foo class contains a Type property. Type property is a enum. public enum Type

I''ve got a List<Foo>. Foo class contains a Type property. Type property is a enum.

  public enum Type
  {
       Arithmetic, Fraction, ...
  }


  public class Foo
  {
      public Type ProblemType
      {
          get; set;
      }
  }

I'd like to ge开发者_运维百科nerate another list where it is sorted by ProblemType, and each one contains Foo clases which belong to the same Type. I can imagine I should use Enumerable, but I don't know how use them.

Thanks in advance


You can use GroupBy() to do that:

List<List<Foo>> groupedLists
    = yourList.GroupBy(foo => foo.ProblemType)
              .OrderBy(group => group.Key)
              .Select(group => group.ToList())
              .ToList();

In passing, I would advise against using Type as the name of your enum, as getting into name conflicts with System.Type is usually not a good idea. You can even name it ProblemType, since writing public ProblemType ProblemType { get; set; } is unambiguous.


To sort by ProblemType, you can try this

var sortedFooList = fooList.OrderBy(f => f.ProblemType);

sortedFooList will be IOrderedEnumerable<Foo>. If you want List<Foo>, just add .ToList() after calling OrderBy().


Assuming you already have a List<Foo>, you can query that list to provide an ordered collection by ProblemType:

List<Foo> myFoos = GetFooList();

var sortedFoos = myFoos.OrderBy(f => f.ProblemType);

sortedFoos is an enumerated collection sorted by Foo.ProblemType.

0

精彩评论

暂无评论...
验证码 换一张
取 消