Recently, while working in C#, I ran into a problem where I had to group elements in a data structure and output the results using select. I kept running into run time errors where nothing was being outputted. After searching and trying different methods, I was able to arrive at a solution.
Let’s assume that we want to output users after grouping them by whether their accounts are active or not. Here’s how we would do that:
var getUsers = User.GetUsers(); // Returns a list of users
var activeUsers = getUsers.Groupby(x => x.Enabled).Select(y => new {
Key = y.Key, //Key here is what we grouped it by (i.e. Enabled)
UserId = y.UserId,
Username = y.UserName,
FirstName = y.FirstName,
LastName = y.LastName
});