I want to retrieve an element or a list of elements from my list without using for or foreach loop, the reason is my list is very big, also, I need to do another loop on the result. In this point of view, algorithmic complexity is not a good idea to use two loops inside each other.
-
how do you determint the element? Index, a condition? – fubo Apr 08 '16 at 11:19
-
HashTable might help you. – zypro Apr 08 '16 at 11:22
-
1indeed I have a list of object, sometimes I need a condition on a property and to get one element I use id. – Apr 08 '16 at 11:22
-
It might not be possible what you want: can you loop through the list only once and at the same time find your item and do the result calculation? Then it is possible. Or, do you really need to have the item before you can do the loop? Then, it's not possible and you are stuck with the performance of two nested loops. – MicroVirus Apr 08 '16 at 11:26
-
it not possible in my case because the collected items are related to each-other. – Apr 08 '16 at 11:30
-
1Show us the declaration of your 'list' !!! – TaW Apr 08 '16 at 11:31
-
Then the answer is that you can't and you need two loops. The answers suggest LINQ, but of course that's just fancy syntax for loops, so it will not change the complexity characteristics. – MicroVirus Apr 08 '16 at 11:32
-
Yes,I think LINQ is the key ^^, thank you guys. – Apr 08 '16 at 11:34
-
@HindHanoda Linq are loops, if you want to avoid to iterate each item of your list you have to make something custom like access by index or a binary search if your list is sortet by the required property – fubo Apr 08 '16 at 11:36
-
This is entirely too vague to give a good answer to. Please try to be more specific. – juharr Apr 08 '16 at 11:50
2 Answers
The answer depends on the mean to determine which element you want. The fact is that a List will have on O(1) complexity if you have the index of the element you want to find; otherwise it will always have a O(n) complexity (LINQ or not).
However, if you need to extract many elements in your collection and then use a loop on them, LINQ will enable you to do it with only one loop (on all the elements of your collection) easily:
foreach (var element in myCollection.Where(myCondition))
If you want to find your element with a smaller complexity than O(n), you should look at HashSet<T>
and Dictionary<TKey, TValue>
.
But your question is not precise enough to give you a more specific answer.

- 1,257
- 11
- 25
if you can to get one element from a list without looping you can use LINQ ( first,firstOrdefault, Single,SingleOrdefault) functions that can give you one element from you list, also if you need more than once you can use where with ToList at the end for the cast.all those functions take as parameters lambda expression. Also check those links to see why I am right:
- http://www.anujvarma.com/replacing-foreach-loops-with-linq-expressionsa-performance-gain/
- http://www.anujvarma.com/linq-versus-loopingperformance/
- http://code-fight.club/fight/7/linq-vs-foreach
As long as you have a big size collection, LINQ is the correct choice.
You can also check this example to see why LINQ is the best choice to handle a big size array '400k elements +' :
Here is the result:
Real run:
TestLINQ count: 499854
0:00:00:00.0170207
TestForeach count: 499854
0:00:00:00.0200297
TestFor count: 499854
0:00:00:00.0198944
The difference between LINQ, For and Foreach will be visible if we use bigger arrays.

- 959
- 1
- 14
- 28
-
5
-
3Yes, but it takes less time than a normal loop. try it and calculate execution time to see the result. – Badro Niaimi Apr 08 '16 at 11:24
-
LINQ is indeed the way to go. Better readable and maintainable code; but a bit slower (in 99% of the cases irrelevant). – L-Four Apr 08 '16 at 11:27
-
@BadroNiaimi That is nonsense. LINQ cannot be faster than a normal (well-written) loop. – MicroVirus Apr 08 '16 at 11:27
-
3I'm pretty sure that LINQ works faster than a normal program, you can try it by yourself because I did more than once and the result was totally different will link the program consume couple of seconds less than normal loop – Badro Niaimi Apr 08 '16 at 11:29
-
Source code for [Find: it's a loop.](http://stackoverflow.com/questions/4369040/c-sharp-difference-between-first-and-find). Hence, not faster. – MicroVirus Apr 08 '16 at 11:31
-
3LINQ is slower than a loop. See http://stackoverflow.com/questions/3156059/linq-statement-faster-than-foreach-loop. But that is actually not an argument to not use it in most cases. – L-Four Apr 08 '16 at 11:32
-
3I would say those are theories. the reality is totally different. I used a stop watch in a program, then I used a normal for and a LINQ function, so with LINQ I got couple of seconds less. – Badro Niaimi Apr 08 '16 at 11:38
-
3@BadroNiaimi - source, or it didn't happen. Sorry, either your tests were wrong or the loop did more than it should. LINQ is just a couple of extension methods. No magic involved. So how could it be faster? – Corak Apr 08 '16 at 11:41
-
1@BadroNiaimi First: LINQ isn't designed to save the computer time. It's designed to save the developer time. As I said before, in most cases performance is a non-argument, because you wouldn't notice the difference; so LINQ *IS* a valid answer but is not more performant. Second, your tests or queries are probably flawed. Maybe interesting to share them. Also see http://www.schnieds.com/2009/03/linq-vs-foreach-vs-for-loop-performance.html. – L-Four Apr 08 '16 at 11:42
-
Hey, everyone look at what I found here, LINQ's performance is better if you have a big size collection, http://www.anujvarma.com/linq-versus-loopingperformance/ – Badro Niaimi Apr 11 '16 at 08:58
-
1@Corak, I think that the links above are more than enough for you. – Badro Niaimi Apr 11 '16 at 09:16
-
@BadroNiaimi - thanks for the additional links, but as you can see, in the "LINQ versus looping–Performance", the `for` loop does something **different** than the `LINQ` code (and the other link from the same site basically just references this). And in the "code-fight.club" link, LINQ won, because it is easier to read and maintain (which is the *point* of LINQ), but **not** because it's faster, which I'm still thoroughly convinced, it isn't. Take a look at [referencesource](http://referencesource.microsoft.com/#system.core/system/linq/Enumerable.cs) at line 956. LINQ *uses* foreach. No magic. – Corak Apr 11 '16 at 12:07
-
To elaborate a bit more, LINQ evaluates lazily, so with `from num in data where num < 100 select num` you just prepare a query which *does not get executed immediatelly* (only "on demand"). So basically, you're doing *nothing*. While `for (int i = 0; i <= iterations; i++) { foreach (int j in data) { if (j < 100) searchResults.Add(j); } }` actually *does* do all the work. – Corak Apr 11 '16 at 12:12
-
2I will do more digging about it, but basing on my personal experience, LINQ win every time performance and code visibility, all the links that you posted before are answers from this site also contain only theories no source no tests, if you wanna do your own test, you should do tests on different lists size with warmup. – Badro Niaimi Apr 11 '16 at 12:43
-
@BadroNiaimi - I understand and encourage you to do so. But the linked referencesource is not a "theory", it is how LINQ is actually implemented. I'm not sure how else to convince you. – Corak Apr 11 '16 at 12:49
-
Try https://dotnetfiddle.net/pxcbHY but copy it to a local (console) application, compile it to release and run it without a debugger. The times should be very close together, with no clear "winner". Especially and by far not as "clear" as the "LINQ versus looping–Performance" link makes it out to be. – Corak Apr 11 '16 at 13:02
-
1well if you noticed in the referencesource they use foreach to implement where so when you use LINQ where indeed is a foreach also for firstOrdefault is a foreach with additional tests to avoid exception, but I don't know where did you find the double loop for followed by foreach!! – Badro Niaimi Apr 11 '16 at 13:03
-
2I told you the test should take the list's size in consideration, because for a small size list foreach work better but for a big one LINQ wins. – Badro Niaimi Apr 11 '16 at 13:06
-
@BadroNiaimi - the `for` followed by `foreach` is from your [link](http://www.anujvarma.com/linq-versus-loopingperformance/). If you check my [dotnetfiddle](https://dotnetfiddle.net/pxcbHY), you see, the size of the list is `400000`, you can put a higher number there if you like. – Corak Apr 11 '16 at 13:33