简体   繁体   中英

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.

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!

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);
}

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();

You can expand Group s 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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM