如何在select语句中获取位置

时间:2009-06-09 13:50:45

标签: c# linq

我正在使用LINQ,如

from a in b.Descendants("SomeNode")
select new MyClass
    {
      isfirst= false, 
      islast = false,
    };

如何在这里获取元素的位置?我基本上想知道哪一个是第一个,哪一个是最后一个元素。

3 个答案:

答案 0 :(得分:2)

像...一样的东西。

var res = b.Select((l, i) => 
          new MyClass { IsFirst = (i == 0), IsLast = (i == b.Count-1) });

......应该有用。

每条评论:将匿名类更改为具体类。这假设IsFirst和IsLast是布尔属性,在名为MyClass的类上有一个setter。

答案 1 :(得分:1)

你必须使用lambda语法。

b.Descendants("SomeNode").Select((pArg, pId) => new { Position = pId});

答案 2 :(得分:0)

LP的解决方案有效,但您也可以用更易读,基于单词的LINQ格式表达:

static class EnumerableExtensions {
    public struct IndexedItem<T> {
        public T Item;
        public int Index;
    }

    public static IEnumerable<IndexedItem<T>> Enumerate<T>(this IEnumerable<T> Data) {
        int i = 0;
        foreach (var x in Data)
            yield return new IndexedItem<T> { Index = i++, Item = x };           
    }
}

现在你可以说:

from a in b.Descendants("SomeNode").Enumerate() 
select new MyClass {
    isFirst = (a.Index == 0), 
    isLast  = (...),
    element = a.Item }