[C#][System.Linq] Some convenient data processing methods (Range, Select)
Because I am used to some convenient methods in Python, I immediately checked whether there are similar methods in C#.
1. Range() method
In Python, range (Start, End, Step) can directly generate an iterable object, which can be used to process certain code blocks that need to be looped multiple times:
(Note: End in the Range method is an open interval, and the actual value of range (1, 10) is (1 ~ 9))
1 for item in range(1, 10 ): 2 print span>(item, end='') 3 # span> Output: 4 # 123456789
The same method can be used in C#:
Enumerable.Range(Start, Count) in the System.Linq namespace
1 foreach(int item in Enumerable.Range(1, 10 )) 2 Console.Write($"{item}="); 3 // Output: 4 // 1=2=3=4=5=6=7=8=9=10=
The parameters in range (Start, End, Step) and Enumerable.Range (Start, Count) have different meanings:
range is start, end, step, and the generated object does not include the End element.
Range: The sequence is start, quantity, that is, starting from 1 and counting backwards 10 numbers, so the result of the above output is 1~10. If it is changed to Range(0, 10), the result will be 0~9.
2. Select() method
It corresponds to the Enumerate() method in Python, that is, while traversing the elements, the corresponding subscript is also assigned to the index:
1 for index, item in enumerate(range(1, 10 )): 2 print(f 'The subscript of element | {item} | is: {index}') 3 # Output: 4 ''' 5 Element | 1 | The subscript is: 0 6 element | 2 The subscript of | is: 1 7 element | 3 The subscript of | is: 2 8 element | 4 The subscript of | is: 3 9 element | 5 The subscript of | is: 4 10 element | 6 The subscript of | is: 5 11 element | 7The subscript of | is: 6 12 element | 8 The subscript of | is: 7 13 element | 9 The subscript of | is: 8 14 '''
It is implemented by the Select() method in C#. The Select method can convert the collection and return a new collection containing the converted elements.
1 foreach (var item in Enumerable.Range(1, 10 ).Select((num, index) => new { Index = index, Num = num })) 2 Console.WriteLine($"Index: {item.Index}, Num: {item.Num}"); 3 4 // Output: 5 //Index: 0, Num: 1 6 //Index: 1, Num: 2 7 //Index: 2, Num: 3 8 //Index: 3, Num: 4 9 //Index: 4, Num: 5 10 //Index: 5, Num: 6 11 //Index: 6, Num: 7 12 //Index: 7, Num: 8 13 //Index: 8, Num: 9 14 //Index: 9, Num: 10
The meaning of the parameters in the Select() method is, in order, element, subscript. If it is written as Select (index, num), then index will represent the element and num will represent the subscript.