个性化阅读
专注于IT技术分析

LINQ distinct方法

本文概述

在LINQ中, 使用Distinct方法或运算符仅从集合中获取不同的元素。

这是LINQ Distinct方法的图形表示。

LINQ distinct方法

LINQ Distinct方法或运算符用于仅从集合中获取不同的元素。

LINQ distinct方法的语法

这是使用不同方法从集合中获取唯一元素的语法。

IEnumerable<int> result = numbers.Distinct();

在上面的语法中, 我们对”数字”集合应用了distinct方法, 以仅从集合中获取distinct元素。

LINQ distinct方法的示例

这是LINQ Distinct方法的示例。

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)
        {
//taking an array named countries type of string having the list of countries 
            string[] countries = { "UK", "India", "Australia", "uk", "india", "USA" };
//apply the Distinct method to find out the different country names 
            IEnumerable<string> result = countries.Distinct(StringComparer.OrdinalIgnoreCase);
    //with the help of foreach loop fetch each element from the list of the array
            foreach (var item in result)
            {
    /*with the help of WriteLine() function print the values of 
    the variable item having the output of the result*/ 
                Console.WriteLine(item);
            }
                Console.ReadLine();
        }

    }

    }

在上面的示例中, 我们使用具有StringComparer.OrdinalIgnoreCase case属性的Distinct方法, 否则, 它将对”国家”集合执行 distinct大小写的操作, 并将”印度”和”印度”视为不同。

输出

LINQ distinct方法

赞(0)
未经允许不得转载:srcmini » LINQ distinct方法

评论 抢沙发

评论前必须登录!