在LINQ中,DISTINCT方法或运算符用于仅从集合中获取不同的元素。
下面是LINQ DISTINCT方法的图形表示。
LINQ DISTINCT方法或运算符用于仅从集合中获取不同的元素。
下面是使用不同方法从集合中获取唯一元素的语法。
IEnumerable<int> result = numbers.Distinct();
在上面的语法中,无涯教程对“numbers”集合应用了 distinct 方法来只从集合中获取不同的元素。
下面是LINQ DISTINCT方法的示例。
链接:https://www.learnfk.comhttps://www.learnfk.com/linq/linq-distinct-method.html
来源:LearnFk无涯教程网
using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Programme2 { static void Main(string[] args) { //采用具有国家列表的名为国家/地区的字符串类型的数组 string[] countries = { "UK", "India", "Australia", "uk", "india", "USA" }; //应用 Distinct 方法找出不同的国家名称 IEnumerableresult = countries.Distinct(StringComparer.OrdinalIgnoreCase); //借助 foreach 循环从数组列表中获取每个元素 foreach (var item in result) { Console.WriteLine(item); } Console.ReadLine(); } } }
在上面的例子中,无涯教程应用了一个带有 StringComparer.OrdinalIgnoreCase 大小写属性的 Distinct 方法,否则,它将对 "countries" 集合执行区分大小写的操作,并将 "India" 和 "india" 视为不同。
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)