4 回答

TA贡献1868条经验 获得超4个赞
您不需要分组,您想要更改列表的顺序。C# 使用该Sort()方法自然地内置了此功能。
根据您的问题,我假设您userList的是List<string>. 既然如此,直接使用代码:
userList.Sort();
但是,假设您userList是 a List<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();
希望能解决问题!

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

TA贡献2037条经验 获得超6个赞
您可以直接使用 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);
}

TA贡献1829条经验 获得超7个赞
Group您可以借助以下内容扩展s SelectMany:
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}
- 4 回答
- 0 关注
- 87 浏览
添加回答
举报