Linq是Language Integrated Query的简称,它是微软在.NET Framework 3.5里面新加入的特性,用以简化查询查询操作。本文主要介绍.NET(C#) 中Linq的Reverse和Distinct操作符。

1、Reverse操作符

Reverse操作符用于生成一个与输入序列中元素相同,但元素排列顺序相反的新序列。

例如,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            List<People> pList = new List<People>();
            People p1 = new People(1, "C", 4);
            People p2 = new People(2, "Java", 7);
            People p3 = new People(3, "Python", 11);
            People p4 = new People(4, "Linux", 1);
            People p5 = new People(5,"CJavaPY",1);
            pList.Add(p1);
            pList.Add(p2);
            pList.Add(p3);
            pList.Add(p4);
            pList.Add(p5);
            List<People> pList1 = new List<People>();
            IEnumerable<People> newList = pList.Reverse<People>();;
            foreach (var item in newList)
            {
                Console.WriteLine(item.Name);              
            }
            Console.ReadKey();
        }
    }
    public class People
    {
        public People(int id, string name, int age)
        {
            this.Id = id;
            this.Name = name;
            this.Age = age;
        }
        public int Id
        {
            get;
            set;
        }
        public string Name
        {
            get;
            set;
        }
        public int Age
        {
            get;
            set;
        }
    }
}

2、Distinct操作符

Distinct操作符类似于SQL语句中的Distinct语句,这里的Distinct操作符也用于去除一个序列中的重复元素。

例如,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
          List<int> listInt = new List<int>();
            listInt.Add(1);
            listInt.Add(1);
            listInt.Add(2);
            listInt.Add(2);
            listInt.Add(2);
            IEnumerable<int> IEInt = listInt.Distinct();
            foreach (var i in IEInt)
            {
                Console.WriteLine(i);       
            }
            Console.ReadKey();
        }
    }
}

推荐文档