Aswini
Aswini

Reputation: 51

Group list items by their name

I have a list with duplicate items. I need to group them in the same order.

i found many solutions in LINQ to group list items based on some key.

For example:-

i have a list like below

tbl1
tbl1
tbl2
tbl3
tbl1
tbl4
tbl2

i need to group it like the below

tbl1
tbl1
tbl1 
tbl1
tbl2
tbl2
tbl3
tbl4

Can this be achieved.

Upvotes: 1

Views: 979

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186678

You can expand Groups with a help of SelectMany:

   var groupedCustomerList = userList
     .GroupBy(u => u.GroupID)     // Grouping
     .SelectMany(group => group)  // Expand groups back (flatten)
     .ToList();

What's going on:

initial:          {tbl1, tbl1, tbl2, tbl3, tbl1, tbl4, tbl2}
after GroupBy:    {Key = "1", {tbl1, tbl1, tbl1}},
                  {Key = "2", {tbl2, tbl2}},
                  {Key = "3", {tbl3}},
                  {Key = "4", {tbl4}},
after SelectMany: {tbl1, tbl1, tbl1, tbl2, tbl2, tbl3, tbl4}

Upvotes: 0

John Bustos
John Bustos

Reputation: 19544

You don't want a grouping, you want to change the order of the list. C# has this naturally built in using the Sort() method.

Based upon your question, I'm ASSUMING your userList is a List<string>. That being the case, just use the code:

userList.Sort();

Assuming, however, that your userList is a List<SomeObject> instead, you could do this using Linq in the following way:

Assuming your object was something like:

class MyObject
{
    public string Name;
    // Whatever other properties
}

you could use:

var userList = new List<MyObject>();
// Whatever extra code...
userList = userList.OrderBy(v => v.Name).ToList();

Hope that does the trick!

Upvotes: 1

YSFKBDY
YSFKBDY

Reputation: 886

You say you want to group them, but the example you give indicates that you need to order them.

If you want to remove duplicate items, you need:

var groupedCustomerList = userList
    .GroupBy(u => u.GroupID)
    .ToList();

But, if you need to order them as shown in the example you need to write something like this:

var groupedCustomerList = userList
    .OrderBy(u => u.GroupID)
    .ToList();

or

var groupedCustomerList = userList.Sort();

Upvotes: 0

Indrit Kello
Indrit Kello

Reputation: 1313

You can use GroupBy() method directly.

List<string> elements = new List<string>() //lets consider them as strings
{
  "tbl1",
  "tbl1",
  "tbl2",
  "tbl3",
  "tbl1",
  "tbl4",
  "tbl2"
};
var groups = elements.OrderBy(x=>x).GroupBy(x => x);//group them according to their value
foreach(var group in groups)
{
  foreach (var el in group) Console.WriteLine(el);
}

Upvotes: 0

Related Questions