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 關注
- 117 瀏覽
添加回答
舉報