Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the basic usage of LINQ in C #

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge of what is the basic use of LINQ in c#. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

1. Screening

LINQ queries are filtered by adding conditional expressions to the where clause, and the where clause can merge multiple expressions.

Var racers = from r in Formula1.GetChampions () where r.Wins > 15 & & (r.Country = = "Brazil" | | r.Country = = "Austria") select r; foreach (var r in racers) {Console.WriteLine ("{0r.Country A}", r);}

The above LINQ expression maps to the extension method of the C # LINQ query:

Var racers = Formula1.GetChampions () .Where (r = > r.Wins > 15 & & (r.Country = = "Brazil" | | r.Country = = "Austria")) .Select (r = > r)

Note that not all queries can use LINQ query syntax, and not all extension methods map to LINQ queries. Advanced queries require the use of extension methods.

two。 Filter with index

An example of a LINQ query that cannot be used is the overloading of the Where () method. In the overload of the WHere () method, you can pass the second parameter, the index. The index is a counter for each result returned by the filter. You can use this index in an expression to perform index-based calculations:

Var racers = Formula1.GetChampions (). Where ((r, index) = > r.LastName.StartsWith ("A") & & index% 2! = 0); foreach (var r in racers) {Console.WriteLine ("{0r.LastName.StartsWith A}", r);} 3. Type screening

For type-based filtering, you can use the OfType () extension method.

Object [] data = {"one", 2,3, "four", "five", 6}; var query = data.OfType (); foreach (var s in query) {Console.WriteLine (s);}

Output:

One four five

Returns only strings from the collection.

4. Compound from clause

If you need to filter based on a member of an object that is itself a series, you can use the compound from clause. For example, the Racer class in the LINQ Foundation (1) (https://www.yisu.com/article/244208.htm) defines an attribute Cars,Cars that is an array of strings.

Select all the champions who drive Ferrari:

Var ferrariDrivers = from r in Formula1.GetChampions () from c in r.Cars where c = "Ferrari" orderby r.LastName select r.FirstName + "" + r.LastName; foreach (var racer in ferrariDrivers) {Console.WriteLine (racer);}

The first from clause accesses the Racer object returned by the Formula1.GetChampions () method, and the second from clause accesses the Cars property of the Racer class to return all sting types of racing.

The C # compiler converts composite from clauses and LINQ queries into SelectMany () extension methods. The SelectMany () extension method can iterate over a sequence in a sequence.

Overloaded version of SelectMany ():

Public static IEnumerable SelectMany (this IEnumerable source, Func collectionSelector, Func resultSelector)

The first parameter is an implicit parameter, which accepts a sequence of Racer objects from the Formula1.GetChampions () method. The second parameter is the collectionSelector delegate, where the internal sequence is defined, which is the sequence of the sequence. In this example, Cars. The third parameter is also a delegate, which is called for each element of the Cars attribute of each Racer object.

Where Cars is an array of strings, the delegate is called with each Racer and each string as a parameter.

Var ferrariDrivers = Formula1.GetChampions (). SelectMany (c = > c.Cars, (r, s) = > new {Racer=r,Car = s}). Where (s = > s.Car = = "Ferrari"). OrderBy (r = > r.Racer.LastName). Select (r = > r.Racer.FirstName + "" + r.Racer.LastName); foreach (var racer in ferrariDrivers) {Console.WriteLine (racer);} 5. Sort

To sort the sequence, you can use the previously used orderby. You can also use the orderrby descending clause (descending).

Var racers = (from r in Formula1.GetChampions () orderby r.Country descending select r); foreach (var racer in racers) {Console.WriteLine ("{0}: {1}, {2}", racer.Country, racer.LastName, racer.FirstName);}

The orderby clause is resolved to the OrderBy () method, and the orderby r.Country descending is resolved to the OrderByDescending () method:

Var racers = Formula1.GetChampions () .OrderByDescending (r = > r.Country) .Select (r = > r)

The OrderBy () and OrderByDescending () methods return IOrderEnumerable. This interface is derived from the IEnumerable interface but contains an additional method, the CreateOrderEnumerable () method. This method is used to further sort the sequence, specifying ascending or descending order in the last parameter:

/ / Summary: / / performs subsequent sorting of elements of System.Linq.IOrderedEnumerable based on a key. / / parameter: / / keySelector: / / the System.Func used to extract the key of each element. / comparer: / / the System.Collections.Generic.IComparer used to compare the position of the key in the return sequence. / descending: / / if true, sort the elements in descending order; if false, sort the elements in ascending order. / Type parameter: / / TKey: / / the type of key generated by keySelector. / returns the result: / / an System.Linq.IOrderedEnumerable whose elements are sorted by key. IOrderedEnumerable CreateOrderedEnumerable (Func keySelector, IComparer comparer, bool descending)

Example:

/ / Create an array of strings to sort. String [] fruits = {"apricot", "orange", "banana", "mango", "apple", "grape", "strawberry"}; / / First sort the strings by their length. IOrderedEnumerable sortedFruits2 = fruits.OrderBy (fruit = > fruit.Length); / / Secondarily sort the strings alphabetically, using the default comparer. IOrderedEnumerable sortedFruits3 = sortedFruits2.CreateOrderedEnumerable (fruit = > fruit, Comparer.Default, false)

You can add as many as you want by further sorting using the ThenBy and ThenByDescending () methods:

Var racers = Formula1.GetChampions (). OrderByDescending (r = > r.Country). ThenByDescending (r = > r.LastName). ThenBy Descending (r = > r.FirstName). Select (r = > r); 6. Grouping

To group query results based on a key value, you can use the group clause.

/ / group r by r.Country into g combines all the drivers according to the Country attribute and defines it as a new set g to access the result information of the group. The / / select clause creates an anonymous type with Country and Count attributes. Country = g.Key Key is r.Country var countries = from r in Formula1.GetChampions () group rby r.Country into g orderby g.Count () descending, g.Key where g.Count () > = 2 select new {Country = g.Key Count = g.Count ()} Foreach (var item in countries) {Console.WriteLine ("{0,-10} {1}", item.Country, item.Count);}

Output:

Use the extension method to do the same, parsing the group r by r.Country clause to the GroupBy () method. In the declaration of the GroupBy () method, it returns an enumerated object that implements the IGrouping interface. The IGrouping interface defines the Key property, so after calling this method, you can access the grouped keyword:

Public static IEnumerable GroupBy (this IEnumerable source, Func keySelector)

Use the GroupBy method:

Var countries = Formula1.GetChampions (). GroupBy (r = > r.Country). OrderByDescending (g = > g.Count ()) .ThenBy (g = > g.Key) .Where (g = > g.Count () > = 2). Select (g = > new {Country = g.Key, Count = g.Count ()}) 7. Group nested objects

If the resulting grouped objects need to contain nested sequences, you can change the select clause to create anonymous types.

/ / the returned object needs to contain not only the country name and the driver attributes, but also the driver collection. / / use from R1 ing orderby r1.LastName select r1.FirstName + "" + r1.LastName internal clause var countries = from r in Formula1.GetChampions () group rby r.Country into g orderby g.Count () descending G.Key where g.Count () > = 2 select new {Country = g.Key, Count = g.Count () Racers = from R1 in g orderby r1.LastName select r1.FirstName + "" + r1.LastName} Foreach (var item in countries) {Console.WriteLine ("{0,-10} {1}", item.Country, item.Count); foreach (var name in item.Racers) {Console.Write ("{0};", name);} Console.WriteLine ();} 8. Internal connection

Using the join clause, you can merge two data sources based on specific conditions, but before you get a list of the two connections.

Use the code of LINQ Foundation (1) (https://www.yisu.com/article/244208.htm)

/ / GetChampions champion racing driver var racers = from r in Formula1.GetChampions () from y in r.Years select new {Year = y, Name = r.FirstName + "" + r.LastName} / / GetContructorChampions wins the championship team var teams = from t in Formula1.GetContructorChampions () from y in t.Years select new {Year = y, Name = t.Name} / / get the drivers and teams who win the championship every year / / connect two data sources var racersAndTeams = (from r in racers join t in teams on r.Year equals t.Year into rt from t in rt.DefaultIfEmpty () orderby r.Year) through the join t in teams on r.Year equals t.Year into rt clause Select new {Year = r.Year Champion = r.Name, Constructor = t = = null? "no constructor championship": t.Name}); Console.WriteLine ("Year Champion\ t\ t Constructor Title"); foreach (var item in racersAndTeams) {Console.WriteLine ("{0}: {1 item.Year, item.Champion, item.Constructor);} 9. Left connection

Use the inner connection to return the result that matches the r.Year equals t.Year. The left connection returns all elements of the left data source, even if there are no matching elements in the data source on the right.

Var racers = from r in Formula1.GetChampions () from y in r.Years select new {Year = y, Name = r.FirstName + "" + r.LastName} Var teams = from t in Formula1.GetContructorChampions () from y in t.Years select new {Year = y, Name = t.Name}; / / the left join is defined by the join and DefaultIfEmpty methods. / / if the query shows that the left data source does not have the same result as the right data source Year Use the DefaultIfEmpty method to define the default value on the right side (empty) var racersAndTeams = (from r in racers join t in teams on r.Year equals t.Year into rt from t in rt.DefaultIfEmpty () orderby r.Year select new {Year = r.Year, Champion = r.Name, Constructor = t = = null? "no constructor championship": t.Name}); Console.WriteLine ("Year Champion\ t\ t Constructor Title"); foreach (var item in racersAndTeams) {Console.WriteLine ("{0}: {1 item.Year, item.Champion, item.Constructor);} 10. Group connection

A group connection is similar to an inner connection, which connects two data sources (such as r.Year equals t.Year) through an item, and a group connection uses a set of items to connect, such as the following example

Pass through

New {FirstName = r.FirstName, LastName = r.LastName} equals new {FirstName = r2.FirstName, LastName = r2.LastName}

Connect two data sources

Var racers = Formula1.GetChampionships () .SelectMany (cs = > new List () {new RacerInfo {Year = cs.Year, Position = 1, FirstName = cs.First.FirstName (), LastName = cs.First.LastName ()}, new RacerInfo {Year = cs.Year, Position = 2 FirstName = cs.Second.FirstName (), LastName = cs.Second.LastName ()}, new RacerInfo {Year = cs.Year, Position = 3, FirstName = cs.Third.FirstName (), LastName = cs.Third.LastName ()}) Var Q = (from r in Formula1.GetChampions () join R2 in racers on new {FirstName = r.FirstName, LastName = r.LastName} equals new {FirstName = r2.FirstName LastName = r2.LastName} into yearResults select new {FirstName = r.FirstName, LastName = r.LastName, Wins = r.Wins, Starts = r.Starts, Results = yearResults}) Foreach (var r in q) {Console.WriteLine ("{0} {1}", r.FirstName, r.LastName); foreach (var results in r.Results) {Console.WriteLine ("{0} {1}", results.Year, results.Position);}} 11. Set operation

The extension methods Distinct (), Union (), Intersect () (get intersection), and Except () are all set operations.

/ / get the champion racing driver static void SetOperations () {/ / define a commission to drive both Ferrari and McLaren. It is used to query the drivers who have won the championship in driving Ferrari and the drivers who have won the championship in driving McLaren Func racersByCar = car = > from r in Formula1.GetChampions () from c in r.Cars where c = = car orderby r.LastName select r Console.WriteLine ("World champion with Ferrari and McLaren"); / / use the Intersect method to obtain the intersection foreach of two data sources (var racer in racersByCar ("Ferrari"). Intersect (racersByCar ("McLaren")) {Console.WriteLine (racer);}} 12. Merge

The Zip () method is new to .NET 4.0.It allows two related sequences to be merged into one with one for this function.

For merging, the first item in the first collection is merged with the first item in the second collection, the second item in the first collection is merged with the second item in the second collection, and so on. If the number of items in the two sequences is different, the Zip () method stops when the end of the smaller set is reached.

The elements in the first collection have a Name attribute, and the elements in the second collection have LastName and Starts attributes.

Using the Zip () method on the racerNames collection requires the second collection, racerNamesAndStarts, as the first parameter. The second parameter is a delegate, which accepts the elements of the first collection through the parameter first and the elements of the second collection through the parameter second. In fact, the code returns a string:

Var racerNames = from r in Formula1.GetChampions () where r.Country = = "Italy" orderby r.Wins descending select new {Name = r.FirstName + "" + r.LastName} Var racerNamesAndStarts = from r in Formula1.GetChampions () where r.Country = = "Italy" orderby r.Wins descending select new {LastName = r.LastName Starts = r.Starts} Var racers = racerNames.Zip (racerNamesAndStarts, (first, second) = > first.Name + ", starts:" + second.Starts); foreach (var r in racers) {Console.WriteLine (r);} 13. Zoning

The partitioning operations of the extension methods Take () and Skip () can be used for paging.

For example, only five drivers are shown on the first page and the next five drivers are shown on the next page.

The Skip (page * pageSize) method is set to the specified index, ignoring the previous data. Take (pageSize) method to display pageSize bar data

Int pageSize = 5; int numberPages = (int) Math.Ceiling (Formula1.GetChampions (). Count () / (double) pageSize); for (int page = 0; page)

< numberPages; page++) { Console.WriteLine("Page {0}", page); var racers = (from r in Formula1.GetChampions() orderby r.LastName, r.FirstName select r.FirstName + " " + r.LastName). Skip(page * pageSize).Take(pageSize); foreach (var name in racers) { Console.WriteLine(name); } Console.WriteLine(); } TakeWhile()和SkipWhile()方法,传递一个委托,满足这个条件的数据就提取或跳转:   public static IEnumerable SkipWhile(this IEnumerable source, Func predicate);14.聚合操作符 聚合操作符(如Count(),Sum(),Min(),Max(),Average(),Aggregate())不返回一个序列,而是返回一个值。 例如,使用Count方法应用于Racer的Years属性,筛选获得冠军次数超过3次的赛车手。因为多次使用r.Years.Count(),所以使用let子句定义了一个变量。 var query = from r in Formula1.GetChampions() let numberYears = r.Years.Count() where numberYears >

= 3 orderby numberYears descending, r.LastName select new {Name = r.FirstName + "" + r.LastName, TimesChampion = numberYears}; foreach (var r in query) {Console.WriteLine ("{0} {1}", r.Name, r.TimesChampion) }

The Aggregate () method passes a delegate, taking each element in the data source as a parameter to the delegate, and accumulating it using the specified function.

15. Conversion operator

The LINQ Foundation (1) (https://www.yisu.com/article/244208.htm) mentions that the query is deferred until the data item is iterated, and the transformation operator is used to execute the query immediately, putting the query results in arrays, lists, and dictionaries.

/ / convert to array var names = new List {"Nino", "Alberto", "Juan", "Mike", "Phil"}; var namesWithJ = (from n in names where n.StartsWith ("J") orderby n select n) .ToList ()

Convert to Lookup

/ / use Car racing attributes as keys Each key is associated with multiple drivers Racer var racers = (from r in Formula1.GetChampions () from c in r.Cars select new {Car = c, Racer = r}) .ToLookup (cr = > cr.Car, cr = > cr.Racer) Foreach (var v in racers) {Console.Write (v.Key+ "."); foreach (var k in racers [v.Key]) {Console.WriteLine (k);}}

An overloaded version of the ToLookup (cr = > cr.Car, cr = > cr.Racer) method passes a key and an element selector

If you need to use LINQ queries on untyped collections, you can use the Cast () method to define strongly typed queries:

Var list = new System.Collections.ArrayList (Formula1.GetChampions () as System.Collections.ICollection); var query = from r in list.Cast () where r.Country = = "USA" orderby r.Wins descending select r; foreach (var racer in query) {Console.WriteLine ("{0pura}", racer);}

Cast () casts the element of System.Collections.IEnumerable to the specified type.

16. Generation operator

The generation operators Range (), Empty (), Repeat () methods are not extension methods, but normal static methods that return the sequence. In LING to Object, these methods are available to the Enumerable class.

The Range () method is used to populate a range of numbers. The first parameter is the starting value, and the second parameter is the number of items to be populated:

Var values = Enumerable.Range (1mai 20)

The result is a collection of 1 to 20.

You can merge this result with other extension methods:

Var values = Enumerable.Range (1Magazine 20) .Select (n = > nasty 3)

The Empty () method returns an iterator that does not return a value, which is used for parameters that require a collection, where you can pass an empty collection to the parameter.

The Repeat () method returns a collection iterator of the specified number of duplicate values.

These are all the contents of the article "what is the basic use of LINQ in c #". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report