Click here to Skip to main content
15,886,664 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello
I have a simple Linq query iterating thou two lists, when the the current item is the same, that item is returned. instead of the item being returned, I want the index of the item to be returned:
var indexes = from item1 in list1
              from item2 in list2
              where item1 == item2
              select item1; /*Instead of the Item of the first list being returned I want it to return the index of the first item*/


how to I archive this?
Posted

You can do it in this way:

C#
IEnumerable<int> indexes = (from item1 in list1
                              from item2 in list2
                              where item1 == item2
                              select list1.IndexOf(item1));


or if you want to return the first matching index, then simply apply the First extension:

C#
int firstIndex = (from item1 in list1
                              from item2 in list2
                              where item1 == item2
                              select list1.IndexOf(item1)).First<int>();


Hope it helped.
 
Share this answer
 
try this

SQL
var indexes = from item1 in list1
                      from item2 in list2
                      where item1 == item2
                      select list1.IndexOf(item1);
 
Share this answer
 
Comments
Red&Black 26-May-11 7:17am    
Thank you very much this did the job (:
Tarun.K.S 26-May-11 7:37am    
Wow, even I answered the same thing much before. Is there anything wrong in my code?

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