search
HomeBackend DevelopmentC#.Net Tutorial.NET Framework-Sample code used by LINQ9 class operators

Linq standardQueryOperator

Language set query Ganmge hteg.ratedQuw, LINQ, integrates the query syntax in the C# programming language, and can use the same Syntax for accessing different data sources. LINQ provides an abstraction layer for different data sources, so the same syntax can be used.

1Filter operator

Filter operator defines the conditions for returning elements.

##where Use predicates to return a Boolean valueOfTypeFilter elements based on type
Filter operator Description
Application examples:

where Usage:

 var racers = from r in Formulal.Racers                         
 where r.Wins > 15 && r.Country == "Brazil" select r;

OfType

Projection OperatorDescription

selectMany##Usage example:
object[] data = {"one", 2, "three", 4, 5, "six"};            
var rtnData = data.OfType<string>(); //返回类型为string的数据元素集合
3 Sorting operatorChange the order of returned elements
##select

select usage selectMany usage
var racers = from r in Formulal.Racers
                         where r.Wins > 15 && r.Country == "Brazil"
                         select new
                         {
                             Name = string.Format("{0} {1}", r.FirstName, r.LastName),
                             Country = r.Country,
                             Wins = r.Wins
                         };   //输出为含有Name,Country,Wins共计3个属性的对象集合


Sort operator

Description

OrderByAscending orderOrderByDescendingDescending sortThenByThe first sorting result is similar, use the second ascending sortThenByDescendingThe first sorting result is similar, use the second descending sortingReverseReverse the order of the elements in the setExample:
            var ferrariDrivers = Formulal.Racers.
            SelectMany(r => r.Cars,
            (r, c) => new { Racer = r, Car = c }).
            Where(r => r.Car == "Ferrari").
            OrderBy(r => r.Racer.LastName).
            Select(r => r.Racer.FirstName + " " + r.Racer.LastName);//筛选出驾驶法拉利的选手集合
Operator is used to merge collections that are not directly related
4 connection

Join OperatorDescription

JoinJoins can be joined based on key selector functions 2 collectionsGroupJoinConnect two collections and combine the resultsResult: Racerj
##
    var racers = from r in Formulal.Racers                          
    where r.Country == "Brazil"
                          orderby r.Wins descending
                          select new
                          {
                              Name = string.Format("{0} {1}", r.FirstName, r.LastName),
                              Country = r.Country,
                              Wins = r.Wins
                          };//国家为巴西,按照胜场次数降序排列
Yearj
Teamj

##Yearj=2004Racerj=Michael SchumacherTeamj =FerrariYearj=2005Racerj=Fernando AlonsoTeamj =RenaultYearj=2006Racerj=Fernando AlonsoTeamj =RenaultRacerj=Kimi RäikkönenRacerj=Lewis HamiltonRacerj=Lewis HamiltonRacerj=Lewis Hamilton##Yearj=2009Racerj=Jenson ButtonTeamj =Brawn GPTeamj =Red Bull RacingTeamj =Red Bull RacingTeamj =Red Bull RacingTeamj =Red Bull Racing5 Combination OperatorPut data in groups
##Yearj= 2007
Teamj =Ferrari Yearj=2008
Teamj =Ferrari Yearj=2014
Teamj =Mercedes Yearj=2015
Teamj =Mercedes
##Yearj=2010 Racerj=Sebastian Vettel
Yearj=2011 Racerj=Sebastian Vettel
Yearj=2012 Racerj=Sebastian Vettel
Yearj=2013 Racerj=Sebastian Vettel
Combining Operator Description

GroupBy

Group elements with a common keyGroupBy usage example: Result: ##Country Count
ToLookUp combines elements by creating a one-to-many dictionary.
//Join连接
            //获取冠军年份在2003年后的选手
            var racer5 = from r in Formulal.Racers                
            from y in r.Years                
            where y > 2003
                select new
                {
                    Year = y,
                    Name = string.Format("{0} {1}", r.FirstName, r.LastName)
                };            //获取冠军年份在2003年后的团队
            var team1 = from r in Formulal.ChampionTeams                         
            from y in r.Years                         
            where y > 2003
                         select new
                         {
                             Year = y,
                             Name = string.Format("{0}", r.Name)
                         };            //连接
            var racerAndTeams = from r in racer5                
            join t in team1 on r.Year equals t.Year                
            select new
                {
                    Yearj= r.Year,
                    Racerj = r.Name,
                    Teamj = t.Name
                };

UK

10

##BrazilFinland3Ifgrouping, it should be written like this: 6QuantifierOperatorIf the element sequence meets the specified conditions, the quantifier operator returns a Boolean value
3
needs to be based on multiple fields
 var countries = from r in Formulal.Racers                            
 group r by r.Country into g                            
 orderby g.Count() descending, g.Key                            
 where g.Count() > 2
                            select new 
                            { 
                                Country = g.Key, 
                                Count = g.Count() 
                            };//获取冠军次数大于2的国家
Composition operator

Description

##AnyDetermine whether there is a Elements that satisfy the predicate function

AllDetermine whether all elements in the set satisfy the predicate functionContainsCheck whether an element exists in the collection
            List<int> intList1 = new List<int>(5) {1, 2, 3, 4, 5};           
            bool any3 = intList1.Any(r => r == 3);//确定集合中是否有3,返回true
            bool any0 = intList1.Any(r => r == 0);//确定集合中是否有0,返回false
            bool allMoreZero = intList1.All(r => r > 0);//确定序列中所有元素都满足大于0,返回true
            bool allMore2 = intList1.All(r => r > 2); //返回false
            bool contains3 = intList1.Contains(3); //元素3是否在集合中,true

7分区操作符

分区操作符,返回一个子集。使用它们可以得到部分结果。

分区运算符 描述
Take 必须制定提取元素的个数
Skip 跳过指定的元素个数,提取其他元素
TakeWhile 提取条件为真的元素
SkipWhile 跳过条件为真的元素
            int pageSize = 5;            
            int numberPages = (int)Math.Ceiling(Formulal.Racers.Count() / (double)pageSize);            
            for (int page = 0; page < numberPages; page++)
            {                var racersPartition =
                    (from r in Formulal.Racers                    
                     orderby r.LastName, r.FirstName                     
                     select r.FirstName + " " + r.LastName).Skip(page * pageSize).Take(pageSize);                       
            }

结果:

Page 0Fernando Alons
Mario Andretti
Alberto Ascari
Jack Brabham
Jenson ButtonPage 1Jim Clark
Juan Manuel Fa
Nino Farina
Emerson Fittipaldi
Mika Hakkinen
Page 2Lewis Hamilton
Mike Hawthorn
Damon Hill
Graham Hill
Phil Hill

8集合操作符(Set operators)

集合操作符返回 一 个集合。除了Distinct之外,其他都需要2个集合。

集合操作符 描述
Distinct 从集合中删除重复的元素
Union 返回出现在其中一个集合中的唯一元素
Intersect 交集
Except 只出现在一个集合中的元素
Zip 通过使用指定的谓词函数合并2个集合

应用举例:

            List<int> intList1 = new List<int>(5) {1, 2, 3, 4, 5,3};            
            List<int> intList2 = new List<int>(3) {2, 5, 0};            
            var delDuplic = intList1.Distinct(); //去重,结果{1,2,3,4,5}
            var unionList = intList1.Union(intList2); //并集,结果{1,2,3,4,5,0}
            var interList = intList1.Intersect(intList2); //交集,结果{2,5}
            var exceptList = intList1.Except(intList2);//差集,结果{1,3,4}
            var exceptList2 = intList2.Except(intList1);//差集,结果{0}
            var unionList2 = intList1.Zip(intList2,((i1, i2) => i1+", "+i2)); 结果:{{1,2}{2,5}{3,0}}

9元素操作符(Element operators)

这些元素操作符仅返回一 个元素。

元素操作符 描述
First 返回第一个满足条件的元素
FirstOrDefault 返回第一个满足条件的元素,但如果没有找到满足条件的元素,就返回类型的默认值
Last 返回最后一个满足条件的元素
LastOrDefault 返回最后一个满足条件的元素,但如果没有找到满足条件的元素,就返回类型的默认值
ElementAt 指定了要返回的元素的位置
ElementAtOrDefault 指定了要返回的元素的位置,但如果没有找到满足条件的元素,就返回类型的默认值
Single 只返回一个满足条件的元素,如果有多个满足条件,就抛出一个异常。
SingleOrDefault 只返回一个满足条件的元素,但如果没有找到满足条件的元素,就返回类型的默认值

应用举例:

List<int> intList1 = new List<int>(5) { 1, 8, 3, 4, 5, 3 };
int firstMore1 = intList1.First(r => r > 1);//结果:8
int firstMore17 = intList1.FirstOrDefault(r => r > 17); //结果:0(因为不存在)
int lastMore3 = intList1.Last(r => r > 3); //结果5
int last = intList1.ElementAt(2); //结果3,(索引从0开始)

10聚合操作符(Aggregate operators)

聚合操作符计算集合的一个值。利用这些聚合操作符 ,可 以计算所有值的总和、所有元
素的个数、值最大和最小的元素 ,以 及平均值等

聚合操作符 描述
Count 所有值的个数
Sum 所有值的综合
Min 所有值的的最小值
Max 所有值的的最大值
Average 所有值的平均数
            public class MyIntClass
            {                
            public string Name { get; set; }                
            public int Integar { get; set; }                
            public MyIntClass(string name, int i)
                {                    
                this.Name = name;                    
                this.Integar = Integar;
                }
            }
            List<MyIntClass> intList1 = new List<MyIntClass>(5) 
            { 
                new MyIntClass("first",1),                
                new MyIntClass("second",8) ,                
                new MyIntClass("third",3) ,                
                new MyIntClass("fourth",4) ,                
                new MyIntClass("fifth",5) ,                
                new MyIntClass("sixth",3) 
            };            
            int count = intList1.Count;            
            int sum = intList1.Sum(r=>r.Integar);            
            int min = intList1.Min(r => r.Integar);            
            int max = intList1.Max(r => r.Integar);            
            double average = intList1.Average(r => r.Integar);

11转换操作符(Conversion operators)

转换操作符将集合转换为数组 :IEnumberable、 IList, IDictionary 等。

Conversion operators 描述
ToArray 集合转化为Array
AsEnumerable 返回类型为IEnumerable
ToList 集合转化为List
ToDictionary 集合转化为Dictionary
Cast 映射

还是上面的例子

         IEnumerable<MyIntClass> ienuList = from r in intList1 where r.Integar > 3 select r; //返回默认的IEnumerable集合
         List<MyIntClass> ienuList2 = (from r in intList1 where r.Integar > 3 select r).ToList(); //返回List
         MyIntClass[] ienuList2 = (from r in intList1 where r.Integar > 3 select r).ToArray();//返回数组
         var dict = (from r in intList1 where r.Integar > 3 select r).ToDictionary(r=>r.Name,r=>r.Integar); 
         //字典,key是name, value:Integar
         IEnumerable<MyIntClass> ienuList2 = (from r in intList1 where r.Integar > 3 select r).AsEnumerable();

12生成操作符(Generation operators)

这些生成操作符返回 一 个新集合

Generation operators 描述
Empty 集合是空的
Range 返回一系列数字
Repeat 返回始终重复一个值的集合
IEnumerable<int> ints = Enumerable.Range(3, 10);
//{3,4,5,6,7,8,9,10,11,12}IEnumerable<int> emptyInts =  Enumerable.Empty<int>();
//生成一个空集合IEnumerable<int> ints2= Enumerable.Repeat(6,8);//生成8个6的集合

附:展示所用到的实体类和数据

选手实体类

   //选手实体类
   public class Racer 
    {        
    public Racer(string firstName = null, string lastName = null, 
    string country = null, int starts = 0,int wins = 0, IEnumerable<int> years = null, IEnumerable<string> cars = null)
        {            
        this.FirstName = firstName;            
        this.LastName = lastName;            
        this.Country = country;            
        this.Starts = starts;            
        this.Wins = wins;            
        var yearList = new List<int>();            
        if (years != null)
            {                
            foreach (var year in years)
                {
                    yearList.Add(year);
                }                this.Years = yearList.ToArray();
            }            if (cars != null)
            {                var carList = new List<string>();                
            foreach (var car in cars)
                {
                    carList.Add(car);
                }                
                this.Cars = carList.ToArray();
            }           public string FirstName { get; set; }           
            public string LastName { get; set; }           //赢得比赛的次数
           public int Wins { get; set; }           //所属国家
           public string Country { get; set; }           //开始做的年龄
           public int Starts { get; set; }           //车型数组
           public string[] Cars { get; private set; }           //赢得冠军的年份
           public int[] Years { get; private set; }   
         }
      }

选手数据

//选手List
        public static List<Racer> Racers = new List<Racer>(40)
        {         
                new Racer("Nino", "Farina", "Italy", 33, 5, new int[] { 1950 }, new string[] { "Alfa Romeo" }),                new Racer("Alberto", "Ascari", "Italy", 32, 10, new int[] { 1952, 1953 }, new string[] { "Ferrari" }),                new Racer("Juan Manuel", "Fangio", "Argentina", 51, 24, new int[] { 1951, 1954, 1955, 1956, 1957 }, new string[] { "Alfa Romeo", "Maserati", "Mercedes", "Ferrari" }),                new Racer("Mike", "Hawthorn", "UK", 45, 3, new int[] { 1958 }, new string[] { "Ferrari" }),                new Racer("Phil", "Hill", "USA", 48, 3, new int[] { 1961 }, new string[] { "Ferrari" }),                new Racer("John", "Surtees", "UK", 111, 6, new int[] { 1964 }, new string[] { "Ferrari" }),                new Racer("Jim", "Clark", "UK", 72, 25, new int[] { 1963, 1965 }, new string[] { "Lotus" }),                new Racer("Jack", "Brabham", "Australia", 125, 14, new int[] { 1959, 1960, 1966 }, new string[] { "Cooper", "Brabham" }),                new Racer("Denny", "Hulme", "New Zealand", 112, 8, new int[] { 1967 }, new string[] { "Brabham" }),                new Racer("Graham", "Hill", "UK", 176, 14, new int[] { 1962, 1968 }, new string[] { "BRM", "Lotus" }),                new Racer("Jochen", "Rindt", "Austria", 60, 6, new int[] { 1970 }, new string[] { "Lotus" }),                new Racer("Jackie", "Stewart", "UK", 99, 27, new int[] { 1969, 1971, 1973 }, new string[] { "Matra", "Tyrrell" }),                new Racer("Emerson", "Fittipaldi", "Brazil", 143, 14, new int[] { 1972, 1974 }, new string[] { "Lotus", "McLaren" }),                new Racer("James", "Hunt", "UK", 91, 10, new int[] { 1976 }, new string[] { "McLaren" }),                new Racer("Mario", "Andretti", "USA", 128, 12, new int[] { 1978 }, new string[] { "Lotus" }),                new Racer("Jody", "Scheckter", "South Africa", 112, 10, new int[] { 1979 }, new string[] { "Ferrari" }),                new Racer("Alan", "Jones", "Australia", 115, 12, new int[] { 1980 }, new string[] { "Williams" }),                new Racer("Keke", "Rosberg", "Finland", 114, 5, new int[] { 1982 }, new string[] { "Williams" }),                new Racer("Niki", "Lauda", "Austria", 173, 25, new int[] { 1975, 1977, 1984 }, new string[] { "Ferrari", "McLaren" }),                new Racer("Nelson", "Piquet", "Brazil", 204, 23, new int[] { 1981, 1983, 1987 }, new string[] { "Brabham", "Williams" }),                new Racer("Ayrton", "Senna", "Brazil", 161, 41, new int[] { 1988, 1990, 1991 }, new string[] { "McLaren" }),                new Racer("Nigel", "Mansell", "UK", 187, 31, new int[] { 1992 }, new string[] { "Williams" }),                new Racer("Alain", "Prost", "France", 197, 51, new int[] { 1985, 1986, 1989, 1993 }, new string[] { "McLaren", "Williams" }),                new Racer("Damon", "Hill", "UK", 114, 22, new int[] { 1996 }, new string[] { "Williams" }),                new Racer("Jacques", "Villeneuve", "Canada", 165, 11, new int[] { 1997 }, new string[] { "Williams" }),                new Racer("Mika", "Hakkinen", "Finland", 160, 20, new int[] { 1998, 1999 }, new string[] { "McLaren" }),                new Racer("Michael", "Schumacher", "Germany", 287, 91, new int[] { 1994, 1995, 2000, 2001, 2002, 2003, 2004 }, new string[] { "Benetton", "Ferrari" }),                new Racer("Fernando", "Alonso", "Spain", 252, 32, new int[] { 2005, 2006 }, new string[] { "Renault" }),                new Racer("Kimi", "Räikkönen", "Finland", 230, 20, new int[] { 2007 }, new string[] { "Ferrari" }),                new Racer("Lewis", "Hamilton", "UK", 166, 43, new int[] { 2008, 2014, 2015 }, new string[] { "McLaren", "Mercedes" }),                new Racer("Jenson", "Button", "UK", 283, 15, new int[] { 2009 }, new string[] { "Brawn GP" }),                new Racer("Sebastian", "Vettel", "Germany", 156, 42, new int[] { 2010, 2011, 2012, 2013 }, new string[] { "Red Bull Racing" })

        };

团队实体类

    [Serializable]    public class Team
    {        public Team(string name, params int[] years)
        {            this.Name = name;            
        this.Years = years;
        }        public string Name { get; private set; }        
        public int[] Years { get; private set; }
    }

团队数据

        //冠军团队List
        public static List<Team> ChampionTeams = new List<Team>()
        {            new Team("Vanwall", 1958),            
        new Team("Cooper", 1959, 1960),            
        new Team("Ferrari", 1961, 1964, 1975, 1976, 1977, 1979, 1982, 1983, 1999, 2000, 2001, 2002, 2003, 2004, 2007, 
                       2008),            
                       new Team("BRM", 1962),            
                       new Team("Lotus", 1963, 1965, 1968, 1970, 1972, 1973, 1978),            
                       new Team("Brabham", 1966, 1967),            
                       new Team("Matra", 1969),           
                        new Team("Tyrrell", 1971),           
                         new Team("McLaren", 1974, 1984, 1985, 1988, 1989, 1990, 1991, 1998),           
                          new Team("Williams", 1980, 1981, 1986, 1987, 1992, 1993, 1994, 1996, 1997),            
                          new Team("Benetton", 1995),            
                          new Team("Renault", 2005, 2006),            
                          new Team("Brawn GP", 2009),            
                          new Team("Red Bull Racing", 2010, 2011, 2012, 2013),           
                           new Team("Mercedes", 2014, 2015)
        };


The above is the detailed content of .NET Framework-Sample code used by LINQ9 class operators. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor