Leron
Leron

Reputation: 9856

How to get the index of element inside nested Lists

I have class which looks like this :

public class Payment
{
    public List<string> Base { get; set; }
    public List<string> Interest { get; set; }
}

Then, later in my code I want to feed a Repeater only with the values from List<string> Base so I try to create an array of anonymous objects using LINQ and I need in this anonymous object to have a property Id where Id = IndexOf(x.Base). So i tried this :

RpBase.DataSource = PymentsList.Select(x => new { Base = x.Base, Id = PymentsList.IndexOf(x.Base) });

But it's not working. Writing this it's starting to make sense that I need to select from the <Base> list, of each x but I don't know how to write it LINQ still it seems to me that this should be doable.

Upvotes: 0

Views: 1149

Answers (2)

Xaruth
Xaruth

Reputation: 4104

You may want something like that ?

RpBase.DataSource = PymentsList.Base.Select((x,i) => new { Base = x, Id = i });

if PymentsList is a list of Payment, use .SelectMany(x => x.Base) instead of .Base

Edit : @Tim.Tang has done the good answer faster ^^

Upvotes: 1

Tim.Tang
Tim.Tang

Reputation: 3188

is this what you want?

RpBase.DataSource = PymentsList.SelectMany(x=>x.Base)
                               .Select((x,i)=>new { Base = x, Id =i}) 

Upvotes: 5

Related Questions