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方法

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_48552.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?