溫馨提示×

C# Collection的LINQ查詢方法

c#
小樊
97
2024-07-13 14:04:25
欄目: 編程語言

在C#中,可以使用LINQ(Language Integrated Query)來查詢集合中的數(shù)據。下面是一些常用的LINQ查詢方法:

  1. Where:使用Where方法可以根據指定的條件篩選集合中的元素。
var result = collection.Where(item => item.Property == value);
  1. Select:使用Select方法可以選擇集合中的某些屬性,并返回一個新的集合。
var result = collection.Select(item => new { Property1 = item.Property1, Property2 = item.Property2 });
  1. OrderBy/OrderByDescending:使用OrderBy或者OrderByDescending方法可以對集合中的元素進行排序。
var result = collection.OrderBy(item => item.Property);
  1. GroupBy:使用GroupBy方法可以根據指定的屬性對集合中的元素進行分組。
var result = collection.GroupBy(item => item.Property);
  1. Join:使用Join方法可以將兩個集合中的元素根據指定的條件進行連接。
var result = collection1.Join(collection2, item1 => item1.Property1, item2 => item2.Property2, (item1, item2) => new { Property1 = item1.Property1, Property2 = item2.Property2 });
  1. Any/All:使用Any方法可以判斷集合中是否存在滿足條件的元素;使用All方法可以判斷集合中的所有元素是否都滿足條件。
var result = collection.Any(item => item.Property == value);

以上是一些常用的LINQ查詢方法,通過使用LINQ可以方便地對集合中的數(shù)據進行查詢、篩選、排序等操作。

0