1

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

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();
4

1 回答 1

7

中的索引GroupBy(...).Select((x,i)=>是该组在所有组中的索引,而不是该组中项的索引。

考虑到购物车中有 50 件商品,您GroupBy根据它们创建了 10 个不同的组ClientForOrdersId。然后索引从 0 开始,以 9 结束。所以你不能使用它,ElementAt因为每个组的大小只有 5 并且你得到ArgumentOutOfRangeException.

我假设你想创建一个List<Client_IncvoiceBalance>结果。您根本不需要ElementAt,但SelectMany在组上。

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();
于 2013-06-01T23:56:38.790 回答