This article is a mirror article of machine translation, please click here to jump to the original article.

View: 2582|Reply: 1

[Source] .NET/C# cleverly picks indexes in foreach

[Copy link]
Posted on 2/1/2024 8:26:18 PM | | | |
introduction

The for and foreach loops are one of the most useful constructs in the C# developer toolbox.
In my opinion, iterating over a collection is more convenient than in most cases.
It works with all collection types, including non-indexable ones (such as , and do not require access to the current element through the index).
But sometimes, an index of the current item is really needed; I ran into this problem some time ago when I used foreach to traverse collections in development. This typically uses one of the following patterns:


It has always annoyed me; Can't we get both values and indexes?
There is a simple solution with Linq and tuples.

Solution 1:

Just write an extension method like this:

Please introduce the above code into the following namespace:

Calling method:

Note: Behind the collectionWithIndex();

Solution 2:

If you find the extension method cumbersome, you can also use Solution 2

It's done, it has a little impact on performance, you can observe the use on demand!!





Previous:Nginx disables TLSv1.0 and TLSv1.1 invalid solutions
Next:Oracle queries return field full caps issues
 Landlord| Posted on 2/24/2024 5:00:44 PM |
.NET 9 pair collectionsAdded the Index extension method, you can get the index directly, refer to:The hyperlink login is visible.

public static System.Collections.Generic.IEnumerable<(int Index, TSource Item)> Index<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);

Download the VS 2022 preview at:The hyperlink login is visible.

.NET 9.0 Preview Download:The hyperlink login is visible.

Create a new .NET 9 console app with the following code:







Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com