简体   繁体   English

按名称对列表项进行分组

[英]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.我在 LINQ 中找到了许多解决方案,可以根据某个键对列表项进行分组。

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. C# 使用Sort()方法自然地内置了这个。

Based upon your question, I'm ASSUMING your userList is a List<string> .根据您的问题,我假设您的userListList<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:但是,假设您的userList是一个List<SomeObject> ,您可以通过以下方式使用 Linq 执行此操作:

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.您可以直接使用 GroupBy() 方法。

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 :您可以在SelectMany的帮助下扩展Group

   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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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