Tips for using LINQ

Source: Internet
Author: User

These skills are summarized here. This section describes how to use LINQ:

  • Initialize an array
  • Traverse multiple arrays in a loop
  • Generate random sequence
  • Generate string
  • Conversion sequence or set
  • Converts a value to a sequence with a length of 1.
  • Traverse all subsets of a sequence

If you are interested in LINQ, please share it in your comments.

1.Initialize an array

In general, we need to initialize the value of the array to the same value or incremental sequence value, or it may be an incremental/decreasing sequence with a step not 1. With LINQ, we can complete all the work in the array initializer without loop!

In the following sample code, the first line of code initializes an array of 10, all elements are-1, and the second line of code initializes B to 0, 1, 2 to 9, the third line of code initializes C as 100, 110, 120 to 190.

Int [] A = enumerable. Repeat (-1, 10). toarray ();

Int [] B = enumerable. Range (0, 10). toarray ();

Int [] C = enumerable. Range (0, 10). Select (I => 100 + 10 * I). toarray ();

Please note: If you initialize a large array, it is best not to consider this elegant method but to use the traditional method instead. This solution of LINQ dynamically generates arrays, so the garbage array needs to be recycled at runtime. That is to say, I always use this technique in the case of small arrays or testing and debugging code.

2.Traverse multiple arrays in a loop

A friend asked me a question about C #: is there a way to traverse multiple sets in a loop? The code is similar to this:

Foreach (var x in array1 ){

Dosomething (X );

}

Foreach (var x in array2 ){

Dosomething (X );

}

In this case, the loop subject will be large and he does not want to repeat the code. However, he does not want to create an array to save all the elements of array1 and array2.

LINQ provides an elegant solution: Concat operations. We can use a single loop to rewrite the above Code, as shown below:

Foreach (var x in array1.concat (array2 )){

Dosomething (X );

}

Note that because of the operations performed by LINQ at the enumeration level, it will not generate a new array to save the elements of array1 and array2. Therefore, in addition to elegance, this solution is very efficient.

3.Generate random sequence

This is a simple technique for generating random N-length sequences:

Random Rand = new random ();

VaR randomseq = enumerable. Repeat (0, n). Select (I => Rand. Next ());

With the latency feature of LINQ, sequences are not computed and saved to arrays. Instead, random numbers are generated on demand during iteration of randomseq.

4.Generate string

LINQ is also a good tool for generating various types of strings. It is useful for testing or debugging when generating strings. Suppose we need to generate a string of N length in the "abcabcabc" method. The solution is elegant with the use of LINQ:

String STR = new string (

Enumerable. Range (0, n)

. Select (I => (char) ('A' + I % 3 ))

. Toarray ());

Petar PetrovAnother interesting way to generate a string using LINQ is provided:

String values = string. Join (string. Empty, enumerable. Repeat (pattern, n). toarray ());

5.Conversion sequence or set

In C # Or VB, we cannot convert sequence from T type to U type, even if T inherits from u class. Therefore, it is difficult to convert list <string> to list <Object>. (To explain why, please refer to the bick Byer post ). However, if you want to convert ienumerable <t> to ienumerable <u>, LINQ has a simple and effective solution:

Ienumerable <string> strenumerable = ...;

Ienumerable <Object> objenumerable = strenumerable. Cast <Object> ();

If you want to convert list to list, LINQ also provides a solution, but it will copy the list:

List <string> strlist = ...;

List <Object> objlist = new list <Object> (strlist. Cast <Object> ());

Chris CavanaghAnother solution is recommended:

VaR objlist = strlist. Cast <Object> (). tolist ();

6.Converts a value to a sequence with a length of 1.

What should we do when we need to convert a single value into a sequence with a length of 1? We can create an array with a length of 1, but I still like the repeat operation of LINQ:

Ienumerable <int> seq = enumerable. Repeat (myvalue, 1 );

7.Traverse all subsets of a sequence

Sometimes, it is useful to traverse all subsets of an array. Subsets and problems, Boolean satisfiable problems, and knapsack problems can be solved simply by traversing all subsets of a sequence.

With LINQ, we can use the following subset of all the ARR arrays in the sound field:

T [] arr = ...;

VaR subsets = from m in enumerable. Range (0, 1 <arr. length)

Select

From I in enumerable. Range (0, arr. length)

Where (M & (1 <I ))! = 0

Select arr [I];

Note: If the number of subsets exceeds int, the code above cannot work. Therefore, this method is used only when you know that the length of ARR cannot exceed 30. If the ARR length exceeds 30, you do not want to traverse all subsets, because it may take several minutes or longer.

Comments and summary

I hope these skills will be useful to you. These sample codes are implemented in C #, but you can easily change them to other. NET languages. However, LINQ is more convenient for languages that support extension methods, lambda expressions, and type inference, such as C # and VB. Every piece of code here is feasible, but I cannot guarantee anything. Please check carefully before using it.

Tips for using LINQ

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.