San*_*San 9 c# linq iqueryable
我有一个IQueryable,它按某种条件排序.现在我想知道IQueryable中特定元素的位置.是否有linq表达式来实现.比如说IQueryable中有10个元素,第6个元素与条件匹配,我想得到数字6.
Mar*_*ers 15
首先用索引选择每个项目,然后过滤项目,最后提取原始索引:
var result = orderedList
.Select((x, i) => new { Item = x, Index = i })
.Where(itemWithIndex => itemWithIndex.Item.StartsWith("g"))
.FirstOrDefault();
int index= -1;
if (result != null)
index = result.Index;
Run Code Online (Sandbox Code Playgroud)
试验台:
class Program
{
static void Main(string[] args)
{
var orderedList = new List<string>
{
"foo", "bar", "baz", "qux", "quux",
"corge", "grault", "garply", "waldo",
"fred", "plugh", "xyzzy", "thud"
}.OrderBy(x => x);
// bar, baz, corge, foo, fred, garply, grault,
// plugh, quux, qux, thud, waldo, xyzzy
// Find the index of the first element beginning with 'g'.
var result = orderedList
.Select((x, i) => new { Item = x, Index = i })
.Where(itemWithIndex => itemWithIndex.Item.StartsWith("g"))
.FirstOrDefault();
int index= -1;
if (result != null)
index = result.Index;
Console.WriteLine("Index: " + index);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Index: 5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7174 次 |
| 最近记录: |