var q = from o in orders join c in customers on o.CustomerId equals c.Id into gj from c in gj.DefaultIfEmpty() // Left Join selectnew { o.Id, o.OrderDate, CustomerName = c?.Name ?? "(未知客戶)" };
foreach (var x in q) Console.WriteLine($"{x.Id}{x.CustomerName}{x.OrderDate:d}");
Join 後的結果只要幾個欄位,匿名型別是最省力的方式。EF Core 會只抓到需要的欄位(投影)
常見於產生行號、比對相鄰元素、分頁編號等。
1 2 3 4 5 6 7 8
var lines = File.ReadAllLines("data.txt");
var withIndex = lines .Select((text, idx) => new { LineNo = idx + 1, Text = text }) .Where(x => !string.IsNullOrWhiteSpace(x.Text));
foreach (var x in withIndex) Console.WriteLine($"{x.LineNo}: {x.Text}");
匿名型別的相等性是結構相等(同屬性名稱與值都相等才相等),很好用來做去重或比較。
1 2 3 4
var unique = products .Select(p => new { p.Sku, p.Color }) // 決定唯一性的鍵 .Distinct() .ToList();
Dapper 常用匿名型別傳參數,寫起來乾淨
1 2 3 4
var rows = connection.Query( "SELECT * FROM Users WHERE Email = @Email AND IsActive = @Active", new { Email = email, Active = true } );