首页 > 编程语言 >.NET(C#) Linq Concat和Union以及Select和SelectMany的使用及区别

.NET(C#) Linq Concat和Union以及Select和SelectMany的使用及区别

时间:2023-11-06 23:56:58浏览次数:50  
标签:Console Name People C# System Linq Union new using

1、Concat操作符

Concat操作符用于连接两个序列,生成一个新序列。

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", 15);
            pList.Add(p1);
            pList.Add(p2);
            pList.Add(p3);
            pList.Add(p4);
            List<People> pList1 = new List<People>();
            People p5 = new People(5,"CJavaPY",16);
            pList1.Add(p5);
            IEnumerable<People> newList = pList.Concat(pList1);
            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、Union操作符

Union操作符用于将两个序列中的元素合并成一个新的序列,新序列将自动去除重复的元素。

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(2);
            listInt.Add(3);
            List<int> listInt1 = new List<int>();
            listInt1.Add(2);
            listInt1.Add(3);
            listInt1.Add(4);
             //Concat的使用
            IEnumerable<int> IEInt = listInt.Concat(listInt1);
            foreach (var i in IEInt)
            {
                Console.WriteLine(i);   
            }
            Console.WriteLine();
            //Union的使用
            IEnumerable<int> IEInt1 = listInt.Union(listInt1);
            foreach (var i in IEInt1)
            {
                Console.WriteLine(i);   
            }
             //根据输出结果可以看出Concat和Union的区别
            Console.ReadKey();
        }
    }
}

3、Select操作符

Select操作符对单个序列或集合中的值进行投影。所谓投影,比如有一个数据集,想用LINQ语法去操作数据集,会写一个LINQ的表达式,表达式会把数据集合中的数据简单的投影到一个变量中,并且可以通过这个变量去筛选数据。

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<Employees> emp = new List<Employees> 
            { 
               new Employees(){Id=Guid.NewGuid(),Name="C",Sex=0,CompanyName="xx技术有限公司"},
               new Employees(){Id=Guid.NewGuid(),Name="Java",Sex=0,CompanyName="xx培训"},
               new Employees(){Id=Guid.NewGuid(),Name="Python",Sex=0,CompanyName="xx集团"}
            };
            //查询语法:不能省略最后的select
            var query = (from p in emp where p.Name.StartsWith("C") select p).FirstOrDefault();
            //查询方法:设计到Lambda表达式,全部返回 可以省略最后的select 延迟加载
            var query1 = emp.Where(p => p.Name.StartsWith("C")).Select(e => new { e.Name,e.CompanyName});
            foreach (var item in query1)
            {
                Console.WriteLine(item.Name);
            }
            //查询方法
            var query2 = emp.Where(p => p.Name.StartsWith("C")).Select(p => p.CompanyName);
            foreach (var item in query2)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
    public class Employees
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public int Sex { get; set; }
        public string CompanyName { get; set; }
    }
}

2、SelectMany操作符

SelectMany操作符用于根据输入序列中的每一个元素,在输出序列中创建相应的零个或者多个元素,与Select操作符不同,Select操作符会根据输入序列中的每一个元素创建一个对应的输出序列元素,而SelectMany操作符可以创建多个。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            List<People> pList = new List<People>();
            People p1 = new People(1, "C", 21);
            People p2 = new People(1, "Java", 22);
            People p3 = new People(1, "Python", 23);
            pList.Add(p1);
            pList.Add(p2);
            pList.Add(p3);
            var newList = pList.SelectMany(p => p.Name);    //newList是一个包含所有p.Name的字符的集合IEnumerable<char>
            foreach (var item in newList)                   //Select是一个元素返回一个字符串,而SelectMany是一个元素返回多个字符            {
            {
                Console.Write(item);
            }
            Console.WriteLine();
            var items = pList.SelectMany((p, i) => i < 2 ? p.Name.ToArray() : new char[] { });  //前两个元素才转成字符输出
            foreach (var i in items)
            {
                Console.Write(i);
            }
            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;
        }
    }
}

3、Select与SelectMany的区别

Select()每一次遍历,输出的是T,然后将所有遍历后得到的T组合成一个IEnumerable<T>SelectMany()每遍历一次,输出的是IEnumerable<T>,然后合并成一个大的IEnumerable<T>

 

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)
        {
            string[] text1 = { "C Java Python", "html css js", "SQL MySQL Oracle" };
            var tokens1 = text1.Select(s => s.Split(' '));
            Console.WriteLine(tokens1);
            //遍历需要两个foreach
            foreach (string[] line in tokens1)
                foreach (string token in line)
                    Console.WriteLine("{0}.", token);
            string[] text2 = { "C Java Python", "html css js", "SQL MySQL Oracle" };
            var tokens2 = text2.SelectMany(s => s.Split(' '));
            Console.WriteLine(tokens2);
            //遍历只需要一个foreach
            foreach (string token in tokens2)
                Console.WriteLine("{0}.", token);
            Console.ReadKey();
        }
    }
}

 

标签:Console,Name,People,C#,System,Linq,Union,new,using
From: https://www.cnblogs.com/wwkk/p/17814107.html

相关文章

  • c/c++数据类型
    intunsignedintcharunsignedcharlonglonglongunsignedlongshortunsignedshortfloatdouble各种指针类型枚举类型struct结构类型union联合类型boolstring类 比如把数据类型比做盒子,定义类型就是存仓什么东西,假如int型把盒子分成4份......
  • 23级ACM实验室第一次招新测试题解
    A.还是HelloWorld?思路:无代码:c++:#include<bits/stdc++.h>usingnamespacestd;intmain(){ cin.tie(0)->ios::sync_with_stdio(0); cout<<"Hello,World!"<<endl; return0;}B.这题真不难,放轻松~思路:无代码:C++:#include<bits/st......
  • .NET C# 9.0 record和with的定义及使用
    C#9引入record,它一种可以创建的新引用类型,而不是类或结构。C#10添加了recordstructs,以便可以将记录定义为值类型。记录与类不同,区别在于record类型使用基于值的相等性。两个记录类型的变量在它们的类型和值都相同时,它们是相等的。with表达式在C#9.0及更高版本中可用,......
  • .NET(C#) LinkedList、Queue<T>和Stack<T>的使用
    本文主要介绍.NET(C#)中,LinkedList链表、Queue<T>队列和Stack<T>堆栈的使用,以及相关的示例代码。1、LinkedList(链表)链表中元素存储内存中是不连续分配,每个元素都有记录前后节点,节点值可以重复,不能通过下标访问,泛型的使用保证类型安全,可以避免装箱拆箱,找元素就只能遍历,查找不方......
  • AtCoder Beginner Contest 327
    A-ab题意:判断字符串中是否有“ab”或者是“ba“#include<bits/stdc++.h>usingnamespacestd;voidsolve(){ intn; cin>>n;strings; cin>>s; if(s.find("ab")!=s.npos||s.find("ba")!=s.npos){ cout<<"Yes"; }else{......
  • NSSCTF Round#11 Basic 密码个人赛复盘
    [NSSRound#11Basic]ez_encABAABBBAABABAABBABABAABBABAAAABBABABABAAABAAABBAABBBBABBABBABBABABABAABBAABBABAAABBAABBBABABABAAAABBAAABABAABABBABBBABBAAABBBAABABAABBAAAABBBAAAABAABBBAABBABABAABABAAAAABBBBABAABBBBAAAABBBBBAB第一眼培根密码试了试但不对,观察长度发现应......
  • .NET(C#) Linq GroupBy和GroupJoin的使用
    Linq是LanguageIntegratedQuery的简称,它是微软在.NETFramework3.5里面新加入的特性,用以简化查询查询操作。本文主要介绍.NET(C#)中Linq的GroupBy和GroupJoin操作符1、GroupBy操作符GroupBy操作符类似于SQL语言仲的GruopBy语句,这里的GroupBy操作符用于将输入序列中的元素进......
  • .NET(C#) Cast和OfType的使用
    Linq是LanguageIntegratedQuery的简称,它是微软在.NETFramework3.5里面新加入的特性,用以简化查询查询操作。本文主要介绍.NET(C#)中Linq的Cast和OfType操作符。1、Cast操作符Cast操作符用于将一个类型为IEnumerable的集合对象转换为IEnumerable<T>类型的集合对象。也就是非......
  • .NET(C#) Linq Range和Repeat的使用
    Linq是LanguageIntegratedQuery的简称,它是微软在.NETFramework3.5里面新加入的特性,用以简化查询查询操作。本文主要介绍.NET(C#)中Linq的Range和Repeat操作符。1、Range操作符Range操作符用于辅助生成一个整数序列。usingSystem;usingSystem.Collections.Generic;usi......
  • .NET(C#) 对象的拷贝(浅拷贝和深拷贝)
    本文主要介绍.NET(C#),对象的拷贝,包括浅拷贝和深拷贝,以及浅拷贝和深拷贝的实现方式,不同的实现方式之间的性能对比。1、浅拷贝和深拷贝浅拷贝是指将对象中的数值类型的字段拷贝到新的对象中,而对象中的引用型字段则指复制它的一个引用到目标对象。如果改变目标对象中引用型字段的值......