tags:

views:

101

answers:

3

Hi, I am using LINQ like

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

How can I get the position of the element here? I basically want to know which one is first and which one is last element.

+1  A: 

You've to use lambda syntax.

b.Descendants("SomeNode").Select((pArg, pId) => new { Position = pId});
Vasu Balakrishnan
+2  A: 

Something like ...

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

... should work.

Per comment: Changed anonymous class to concrete class. This assumes that IsFirst and IsLast are boolean properties with a setter on a class called MyClass.

JP Alioto
I got this thing but the problem is In this case I need to use anonymous class. Also I am using LINQ to XML
Tanmoy
Oh. Its working. Thanks :)
Tanmoy
A: 

LP's solution works, but you can also express this in the more readable, word-based LINQ-form:

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 };           
    }
}

Now you can say:

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