如何获取嵌套列表中的元素索引

时间:2014-08-20 08:53:01

标签: c# linq

我的课程看起来像这样:

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

然后,在我的代码中稍后我想仅使用Repeater中的值提供List<string> Base,因此我尝试使用LINQ创建一个匿名对象数组,我需要在此匿名对象,其中Id属性为Id = IndexOf(x.Base)。所以我试过这个:

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

但它没有用。写下来之后,我需要从每个<Base>的{​​{1}}列表中进行选择,但我不知道如何编写它x在我看来,这应该是可行的。

2 个答案:

答案 0 :(得分:5)

这就是你想要的吗?

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

答案 1 :(得分:0)

你可能想要这样的东西吗?

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

如果PymentsListPayment的列表,请使用.SelectMany(x => x.Base)代替.Base

编辑: @Tim.Tang更快地做了很好的答案^^

相关问题