按名称对项目列表

问题描述 投票:1回答:4

我有一个包含重复项目的列表。我需要按照相同的顺序对它们进行分组。

我在LINQ中发现了许多解决方案,可以根据某些键对列表项进行分组。

例如:-

我有一个如下所示的列表

tbl1
tbl1
tbl2
tbl3
tbl1
tbl4
tbl2

我需要像下面这样分组

tbl1
tbl1
tbl1 
tbl1
tbl2
tbl2
tbl3
tbl4

这可以实现吗?

c# asp.net list grouping
4个回答
1
投票

您不想进行分组,您想要更改列表的顺序。 C#使用Sort()方法自然内置。

根据你的问题,我假设你的userList是一个List<string>。既然如此,只需使用代码:

userList.Sort();

但是,假设您的userListList<SomeObject>,您可以使用Linq以下列方式执行此操作:

假设你的对象是这样的:

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

你可以使用:

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

希望这样做!


0
投票

您可以直接使用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);
}

0
投票

您说您要对它们进行分组,但您给出的示例表明您需要对它们进行排序。

如果要删除重复项,则需要:

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

但是,如果您需要按照示例中的说明对它们进行排序,则需要编写如下内容:

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

要么

var groupedCustomerList = userList.Sort();

0
投票

你可以借助Group扩展SelectManys:

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

这是怎么回事:

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}
© www.soinside.com 2019 - 2024. All rights reserved.