0

I have list of class objects similar

 public class MyClass
    {
        public int UserId { get; set; }
        public int ItemId { get; set; }
        public string ItemName { get; set; }
    }

I have list of this, where I want to group them by UserId. Result I am after is sets of List<MyClass> where each list is by user

I have applied the group by but not sure how the select should be

  var group = items.GroupBy(g => g.UserId).
                Select(s=> new MyClass { 
                UserId = s.Key,
              
                }).ToList();

Sample data

  var items = new List<MyClass>
            {
                new MyClass{UserId = 100, ItemId = 245, ItemName = "ABC"},
                new MyClass{UserId = 100, ItemId = 125, ItemName = "ABCff"},
                new MyClass{UserId = 150, ItemId = 233, ItemName = "AweBC"},
                new MyClass{UserId = 100, ItemId = 233, ItemName = "ABweweC"}
            };

Here I would expect two sets of List<MyClass> one list with userid 100 and other with 150 and each list will have 2 class objects

user12073359
  • 289
  • 1
  • 11

2 Answers2

2

You can create a dictionary with UserId as it's key:

var groups = items.GroupBy(c => c.UserId)
                  .ToDictionary(g => g.Key, g => g.ToList());

Now for example, the following:

 Console.WriteLine(String.Join(Environment.NewLine, groups[100]));

Will print out:

100 245 ABC
100 125 ABCff
100 233 ABweweC
InBetween
  • 32,319
  • 3
  • 50
  • 90
1

I think you are after this which will give you List<List<MyClass>>

var group = items.GroupBy(g => g.UserId).Select(s => s.ToList());
huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99