0

This snippet below checks if eCode (an integer) is equal to any element in list1<int> and if yes, it does something. My question is the following.. what would be a linq implementation of this? I'm new to C# and Linq and not sure how to proceed.

for (int i = 0; i < list1.Count; i++)
{
    if (list1[i] == eCode)
    {
       // do something
    }
}
1
  • 5
    LINQ isn't for creating side effects, it's for filtering out data. If you want to change anything inside your if condition, you shouldn't be using LINQ. Commented Jun 17, 2015 at 17:04

4 Answers 4

6

You can retain the loop but convert the conditional statement into a LINQ Where clause:

foreach (var item in list1.Where(l => l == eCode))
{
    // Do something with each item
}
Sign up to request clarification or add additional context in comments.

3 Comments

Right, but we already know that the items are ints, so the equality checks are trivial. What seems to be important are the indices of items that match eCode, and you can't do anything interesting with these indices using pure LINQ.
He's not looking at the indeces, he's using the index to get the value and then compare it - unless I'm misreading the code posted which is entirely possible! list1[i] returns the value of that list item.
Ah well maybe I was reading too much into the use of a for loop and then the index i. I was thinking, "if the index didn't matter, then this would just be a foreach loop, so therefore the index must matter!". However, of course, it could simply be that the asker didn't know of a better way. I'm sure you're right, and so I upvoted.
3

This is effectively the same as the answer from Stephen Kennedy, but I sometimes like this syntax. Usually for more complicated things, but still:

foreach (var item in from l in list1
                     where l == eCode
                     select l)
{
    // Do something with each item
}

Comments

-1

I think the below snippet is what you are looking for:

List<int> i = new List<int>() { 1, 2, 3 };
int eCode = 3;
bool result = i.Any(x => x == eCode);

Comments

-2

This is using the LINQ extension methods, not actual LINQ.

if (list1.Any(i => i == eCode))
{
    // do something
}

1 Comment

This works if the requirement is that at least one item fits the criteria, but the loop in the question technically runs do something on every match.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.