按名称对列表项进行分组

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


我在 LINQ 中找到了很多基于某些键对列表项进行分组的解决方案。


例如:-


我有如下列表


tbl1

tbl1

tbl2

tbl3

tbl1

tbl4

tbl2

我需要像下面这样分组


tbl1

tbl1

tbl1 

tbl1

tbl2

tbl2

tbl3

tbl4

这能实现吗。


慕尼黑8549860
浏览 130回答 4
4回答

MYYA

您不需要分组,您想要更改列表的顺序。C# 使用该Sort()方法自然地内置了此功能。根据您的问题,我假设您userList的是List<string>. 既然如此,直接使用代码:userList.Sort();但是,假设您userList是 a List<SomeObject>,您可以通过以下方式使用 Linq 执行此操作:假设你的对象是这样的:class MyObject{&nbsp; &nbsp; public string Name;&nbsp; &nbsp; // Whatever other properties}你可以使用:var userList = new List<MyObject>();// Whatever extra code...userList = userList.OrderBy(v => v.Name).ToList();希望能解决问题!

慕勒3428872

你说你想对它们进行分组,但你给出的例子表明你需要对它们进行排序。如果你想删除重复的项目,你需要:var groupedCustomerList = userList&nbsp; &nbsp; .GroupBy(u => u.GroupID)&nbsp; &nbsp; .ToList();但是,如果您需要按照示例所示对它们进行排序,则需要编写如下内容:var groupedCustomerList = userList&nbsp; &nbsp; .OrderBy(u => u.GroupID)&nbsp; &nbsp; .ToList();要么var groupedCustomerList = userList.Sort();

阿晨1998

您可以直接使用 GroupBy() 方法。List<string> elements = new List<string>() //lets consider them as strings{&nbsp; "tbl1",&nbsp; "tbl1",&nbsp; "tbl2",&nbsp; "tbl3",&nbsp; "tbl1",&nbsp; "tbl4",&nbsp; "tbl2"};var groups = elements.OrderBy(x=>x).GroupBy(x => x);//group them according to their valueforeach(var group in groups){&nbsp; foreach (var el in group) Console.WriteLine(el);}

吃鸡游戏

Group您可以借助以下内容扩展s SelectMany:&nbsp; &nbsp;var groupedCustomerList = userList&nbsp; &nbsp; &nbsp;.GroupBy(u => u.GroupID)&nbsp; &nbsp; &nbsp;// Grouping&nbsp; &nbsp; &nbsp;.SelectMany(group => group)&nbsp; // Expand groups back (flatten)&nbsp; &nbsp; &nbsp;.ToList();这是怎么回事:initial:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {tbl1, tbl1, tbl2, tbl3, tbl1, tbl4, tbl2}after GroupBy:&nbsp; &nbsp; {Key = "1", {tbl1, tbl1, tbl1}},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {Key = "2", {tbl2, tbl2}},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {Key = "3", {tbl3}},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {Key = "4", {tbl4}},after SelectMany: {tbl1, tbl1, tbl1, tbl2, tbl2, tbl3, tbl4}
打开App,查看更多内容
随时随地看视频慕课网APP