Last active
August 8, 2018 09:28
-
-
Save poychang/e08687136dddd3a50cebd241164e95c7 to your computer and use it in GitHub Desktop.
[利用 LINQ GroupBy 快速分組歸類] 指定欄位將清單做分組,如同 SQL 語法中的 GROUP BY #dotnet #csharp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var data = new List<DemoModel>() { | |
new DemoModel{ Status ="A", Name ="1" }, | |
new DemoModel{ Status ="A", Name ="2" }, | |
new DemoModel{ Status ="B", Name ="3" }, | |
new DemoModel{ Status ="C", Name ="4" }, | |
new DemoModel{ Status ="B", Name ="5" } | |
}; | |
// Original: | |
// [ | |
// { "Status": "A", "Name": "1" }, | |
// { "Status": "A", "Name": "2" }, | |
// { "Status": "B", "Name": "3" }, | |
// { "Status": "C", "Name": "4" }, | |
// { "Status": "B", "Name": "5" } | |
// ] | |
data | |
.GroupBy(g => g.Status) | |
.ToDictionary(o => o.Key, o => o.ToList()) | |
.Dump(); | |
// Transform: | |
// { | |
// "A": [ | |
// { "Status": "A", "Name": "1" }, | |
// { "Status": "A", "Name": "2" } | |
// ], | |
// "B": [ | |
// { "Status": "B", "Name": "3" }, | |
// { "Status": "B", "Name": "5" } | |
// ], | |
// "C": [ | |
// { "Status": "C", "Name": "4" } | |
// ] | |
// } | |
} | |
class DemoModel | |
{ | |
public string Name { get; set; } | |
public string Status { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment