C# 如何获取组中项目的索引

C# 如何获取组中项目的索引,c#,linq,C#,Linq,下面的代码给了我一个参数超出范围的异常。我正在尝试使用ElementAt exension方法获取当前索引的某些项。我在这里遗漏了什么: var orders = cart.GroupBy(x => x.ClientForOrdersId).Select ((x, i) => new Client_InvoiceBalance() { IsMainClient

下面的代码给了我一个参数超出范围的异常。我正在尝试使用ElementAt exension方法获取当前索引的某些项。我在这里遗漏了什么:

var orders = cart.GroupBy(x => x.ClientForOrdersId).Select
            ((x, i) =>
             new Client_InvoiceBalance()
                 {
                     IsMainClient = x.Key == x.ElementAt(i).MainClientId ? true : false,
                     MainClientId = x.ElementAt(i).MainClientId,
                     OtherClientId = x.ElementAt(i).ClientForOrdersId,
                     InvoiceOrderNumber = orderNumber,
                     IsPaidInFull = false
                 }).ToList();
GroupBy…Selectx,i=>中的索引是所有组中组的索引,而不是组中项目的索引

假设购物车中有50个项目,您的GroupBy根据其ClientForOrdersId创建10个不同的组。然后索引以0开始,以9结束。因此您不能在ElementAt中使用它,因为每个组的大小只有5,并且您得到ArgumentOutOfRangeException

我假设您希望创建一个列表作为结果。您根本不需要element,只需在组中选择many

List<Client_IncvoiceBalance> balances = cart
    .GroupBy(x => x.ClientForOrdersId)
    .SelectMany((g, iGroup) => // iGroup is the index of the group
        g.Select((x, iItem) => // iItem is the index of each item in the group
             new Client_InvoiceBalance()
             {
                 IsMainClient = g.Key == x.MainClientId,
                 MainClientId = x.MainClientId,
                 OtherClientId = x.ClientForOrdersId,
                 InvoiceOrderNumber = orderNumber,
                 IsPaidInFull = false
             }
        )).ToList();
GroupBy…Selectx,i=>中的索引是所有组中组的索引,而不是组中项目的索引

假设购物车中有50个项目,您的GroupBy根据其ClientForOrdersId创建10个不同的组。然后索引以0开始,以9结束。因此您不能在ElementAt中使用它,因为每个组的大小只有5,并且您得到ArgumentOutOfRangeException

我假设您希望创建一个列表作为结果。您根本不需要element,只需在组中选择many

List<Client_IncvoiceBalance> balances = cart
    .GroupBy(x => x.ClientForOrdersId)
    .SelectMany((g, iGroup) => // iGroup is the index of the group
        g.Select((x, iItem) => // iItem is the index of each item in the group
             new Client_InvoiceBalance()
             {
                 IsMainClient = g.Key == x.MainClientId,
                 MainClientId = x.MainClientId,
                 OtherClientId = x.ClientForOrdersId,
                 InvoiceOrderNumber = orderNumber,
                 IsPaidInFull = false
             }
        )).ToList();

GroupBy中的索引….Selectx,i=>是所有组中组的索引,而不是组中项目的索引。那么是否有方法访问项目?请向我们提供ClientForOrdersId类的结构,并解释您想要实现什么这只是一个平面属性的标准列表。@user1206480:您想创建一个列表作为结果吗?GroupBy中的索引…Selectx,i=>是所有组中该组的索引,不是组中项目的索引。那么有没有办法访问这些项目?请向我们提供ClientForOrdersId类的结构,并解释您想要实现什么。这只是一个平面属性的标准列表。@user1206480:您想创建一个列表作为结果吗?这绝对解决了问题。从没有到现在。谢谢你的时间,这绝对解决了问题。从没有到现在。谢谢你抽出时间。