[C# Lambda] List使用方法
using System; using System.Collections.Generic; using System.Linq; public class MyClass { public string StringField1 { get; set; } public string StringField2 { get; set; } public int NumberField { get; set; } } class Program { static void Main() { List<MyClass> myObjects = new List<MyClass> { new MyClass { StringField1 = "A", StringField2 = "X", NumberField = 10 }, new MyClass { StringField1 = "B", StringField2 = "Y", NumberField = 20 }, new MyClass { StringField1 = "A", StringField2 = "X", NumberField = 30 } }; var groupedAndSelected = myObjects .GroupBy(obj => new { obj.StringField1, obj.StringField2 }) .Select(group => new { GroupFields = group.Key, SelectedFields = group.Select(obj => new { obj.NumberField }), Total = group.Sum(obj => obj.NumberField) }) .Where(result => result.GroupFields.StringField1 == "A" && result.GroupFields.StringField2 == "X"); foreach (var result in groupedAndSelected) { Console.WriteLine($"Group: StringField1 = {result.GroupFields.StringField1}, StringField2 = {result.GroupFields.StringField2}"); foreach (var selected in result.SelectedFields) { Console.WriteLine($"Selected Field: NumberField = {selected.NumberField}"); } Console.WriteLine($"Total: {result.Total}"); } } }
執行結果:
留言
張貼留言