Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
3.00/5 (3 votes)
See more:
I have a integer list
Dim list = {3,8,9,1,8,6,1}.tolist
I want select index of certain number. For example for 8, i want get of index numbers of 8s
in this example 1 and 4.

How can i write linq query for that? Thanks.

What I have tried:

Dim list = {3,8,9,1,8,6,1}.tolist

Dim indexes = list.Where(Function(x) x = 8).Select(Function(x) list.IndexOf(8)).ToList()

After execute I got {1,1} but i want {1,4}
Posted
Updated 11-Oct-21 13:18pm
v3
Comments
BillWoodruff 11-Oct-21 17:55pm    
And, what happened when you tried that ?
gacar 11-Oct-21 18:56pm    
I got {1,1}

1 solution

While you could use Linq (Select with Index parameter), in this case simple enumeration could be faster:
List<int> list = new List<int>();
for (int i = 0; i < list.Count; i++)
{
    if( list[i] == 8) ndxmatches.Add(i);
}
Dim list As List(Of Integer) = New List(Of Integer)()
For i As Integer = 0 To list.Count - 1
    If list(i) = 8 Then ndxmatches.Add(i)
Next
 
Share this answer
 
v2
Comments
gacar 11-Oct-21 19:22pm    
Thanks for answer. Yes probably.
George Swan 12-Oct-21 9:33am    
Here is the Linq query in C#
var indexes = list.Select((x, i) => i).Where((i)=>list[i]==8);
BillWoodruff 12-Oct-21 10:49am    
Hi George, If you posted that as an answer, I'd upvote it :)

There are lots of ways to skin this cat:

var match8 = Enumerable.Range(0, list.Count)
Where(i => list[i] == 8);

My students have trouble "getting" Select with Index; they look at code that works, like yours, and ask: "why is the variable 'x' never used after the '=>' ?"

If I use Select with Index, I am creating an internal IEnumerable structure that will need to be evaluated to use its contents/data by calls to for/foreach/tolist, etc. In this case, the result i want is only the matching indexes, The Select statement in your code returns only an IEnumerable of indexes.

It seems simpler to use a for loop here, and, for me simpler is usually better. imho, Select with Index is a powerful tool for use when you wish to create more complex structures ... structures you will make full use of their internal data.

i stand ready to change my mind :)
George Swan 12-Oct-21 10:54am    
Bill, I think your answer is the best approach, that is why I didn't post my reply as an answer
BillWoodruff 12-Oct-21 11:47am    
Hi, I think a range of answers is valuable for everyone in the long-run. cheers, Bill

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900