📜 ⬆️ ⬇️

LINQ to Objects with examples

It would seem that the .NET Framework 3.5 and the revolutionary LINQ in particular appeared to developers for a long time, but not all my colleagues still have a clear idea of ​​what it is and what it is “eating” with. Therefore, I decided to write some introductory article for C # programmers, to illustrate with visual examples how LINQ saves time on routine things such as sorting, aggregation, search, etc.

First, let's define what we are talking about LINQ to Objects. LINQ to SQL, XML, Entities, etc. This article is not considered, although I am sure that most of the examples will work there. In addition, starting with Silverlight 2.0, LINQ to Objects is available there.

LINQ to Objects connects to the project by assembling System.Core.dll + System.Linq namespace, implemented as a set of additional methods for any classes compatible with the IEnumerable <T> interface. IEnumerable <T> is a strongly typed version of the amorphous IEnumerable, which appeared in the .NET Framework 1.0. IEnumerable <T> is implemented in such standard classes as typed Collection <T>, List <T>, unique HashSet <T>, Dictionary <K, V> dictionaries, etc.

In order to convert IEnumerable (for example, ancient ArrayList) to IEnumerable <T>, there are two possibilities:
')
Cast <T> - converts any enumeration into a strongly typed version, using strict type conversion.

object [] values = new object [] {"1", "2", "3", "AAA", 5};
IEnumerable < string > strings = values.Cast< string >(); // c , string

The analogue Cast <T> in SQL-like LINQ syntax looks like this:

IEnumerable < string > strings = from string x in values select x;

OfType <T> - converts any enumeration into a strongly typed version using weak type conversion, i.e. skipping non-type T elements.

object [] values = new object [] { "1" , "2" , "3" , "AAA" , 5};
IEnumerable < string > strings = values.OfType< string >(); // , string

Where <T> - filtering by the specified criterion.

object [] values = new object [] { "1" , "2" , "3" , "AAA" , 5, "ABB" };
IEnumerable < string > strings = values.OfType< string >().Where(i => i.StartsWith(“A”)); // , A

First <T> and Last <T> - extract the first and last element of the enumeration. Fill up with an exception, if the combing does not contain elements.

var values = new [] { "1" , "AAA" , "2" , "3" , "ABB" };
IEnumerable < string > strings = values.Where(i => i.StartsWith(“A”));
string AAA = strings.First();
string ABB = strings.Last();


FirstOrDefault <T> and LastOrDefault <T> - extract the first and last element of the enumeration. They work even if the enumeration contains no elements, in this case return default (T), which corresponds to null for reference types, 0 for numeric types, empty structures for structures.

Fist <T> , Last <T> , FirstOrDefault <T> , LastOrDefault <T> have an additional overloaded call option that accepts the lambda filtering criteria function.

var values = new [] { "1" , "2" , "3" , "AAA" , "ABB" };
string AAA = values.FirstOrDefault(i => i.StartsWith( "A" ));


To find out whether there are elements that satisfy a condition, you can use the Any <T> method:

var values = new [] { "1" , "2" , "3" , "AAA" , "ABB" };
bool hasAAA = values.Any(i => i.StartsWith(“A”)); // true


The same method can be used to check the enumeration for the presence of elements:

var values = new [] { "1" , "2" , "3" , "AAA" , "ABB" };
bool hasItems = values.Any(); // true


To find out whether all elements satisfy a condition, you can use the All <T> method:

var values = new [] { "1" , "2" , "3" , "AAA" , "ABB" };
bool hasAAA = values.All(i => i.StartsWith( "A" )); // false

Calculate the number of elements that meet a specific criterion can be as follows:

var values = new [] { "1" , "2" , "3" , "AAA" , "ABB" };
int countAAA = values.Count(i => i.StartsWith( "A" )); // 2

The condition can be omitted, then all elements will be counted:

int countAll = values.Count(); // 5, , :)

It is very convenient to sort the elements with OrderBy <T> and OrderByDescending <T> :

var values = new [] { "1" , "2" , "3" , "AAA" , "ABB" };
IEnumerable < string > strings = values.OrderBy(i => i.Length);

Sort by several criteria:

var values = new [] { "1" , "2" , "3" , "AAA" , "ABB" , "5" , "6" };
IEnumerable < string > strings = values.OrderBy(i => i.Length).ThenBy(i => i);

The same, but in SQL-like syntax:

IEnumerable < string > strings = from s in values order by s.Lenght, s select s;

You can remove duplicates from a listing using the Distinct <T> method:

var values = new [] { "1" , "1" , "2" , "2" , "3" , "3" , "3" };
IEnumerable < string > strings = values.Distinct(); // "1", "2", "3"

One of the variants of this method takes Comparer <T>, i.e. You can, for example, delete duplicate lines without checking for a register:

var values = new [] { "A" , "B" , "b" , "C" , "C" , "c" , "C" };
IEnumerable < string > strings = values.Distinct(StringComparer.OrdinalIgnoreCase); // "A", "B", "C"

Expand the enumeration “to the forest in front”:

var values = new [] { "A" , "B" , "C" , "C" };
IEnumerable < string > strings = values.Reverse(); // "C", "C", "B", "A"

Here are briefly some examples of using LINQ to Objects. I hope the examples are eloquent enough to excite your interest in further studying and using LINQ to Objects ...

(to be continued)

Source: https://habr.com/ru/post/81592/


All Articles