在LINQ查询中返回索引? [英] Return index in LINQ query?

查看:82
本文介绍了在LINQ查询中返回索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好
我有一个简单的Linq查询,它迭代了两个列表,当当前项目相同时,将返回该项目.而不是返回项目,我希望返回项目的索引:

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?

推荐答案

您可以通过以下方式进行操作:

You can do it in this way:

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



或者如果您想返回第一个匹配的索引,则只需应用First扩展名:



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

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



希望对您有所帮助.



Hope it helped.


尝试一下

try this

var indexes = from item1 in list1
                      from item2 in list2
                      where item1 == item2
                      select list1.IndexOf(item1);


这篇关于在LINQ查询中返回索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆