如何在LINQ选择中生成序列号?

时间:2016-01-28 08:56:35

标签: c# linq

我很难使用Linq Select为我的列表生成序列号。

我尝试使用普通变量i然后在里面增加但是它不起作用。

var grouped = (from x in jOMACDetails
                       group x by new { x.MAWorkCode, x.ConstructionNumber } into g
                       let f = g.First()
                       select new UtilityReceivingReportDetailEntity
                       {
                           DefaultAccountCode = string.IsNullOrWhiteSpace(f.AccountTitleCode) ? f.AccountTitleName.Trim() : f.AccountTitleCode.Trim(),
                           CompanyID = CurrentContext.CurrentCompanyID,
                           RRNumber = socnumber.Trim(),
                           RRSequenceNumber = (short)???, // <---- Here is the container the I need to be sequence
                           //...............
                       }).AsEnumerable();

有人可以帮我这个吗? 提前谢谢

2 个答案:

答案 0 :(得分:10)

您可以尝试Select()重载,通过自动合并元素索引,将序列的每个元素投影到新表单中:

var grouped = jOMACDetails.GroupBy(x => new { x.MAWorkCode, x.ConstructionNumber })
    .Select(g => g.First())
    .Select((r, index) => new UtilityReceivingReportDetailEntity
        {
           DefaultAccountCode = string.IsNullOrWhiteSpace(r.AccountTitleCode) ? r.AccountTitleName.Trim() : r.AccountTitleCode.Trim(),
           CompanyID = CurrentContext.CurrentCompanyID,
           RRNumber = socnumber.Trim(),
           RRSequenceNumber = index
        })
    .AsEnumerable();

可悲的是,没有任何查询表达式使用该重载。所以,我用方法语法写了我的答案。但是,如果您愿意,可以在完成查询表达式后使用.Select。但是,恕我直言,没有必要。

答案 1 :(得分:2)

你在寻找这个吗?

var i = 0;
var grouped = (from x in jOMACDetails
    group x by new { x.MAWorkCode, x.ConstructionNumber } into g
    let f = g.First()
    select new UtilityReceivingReportDetailEntity
    {
        DefaultAccountCode = string.IsNullOrWhiteSpace(f.AccountTitleCode) ? f.AccountTitleName.Trim() : f.AccountTitleCode.Trim(),
        CompanyID = CurrentContext.CurrentCompanyID,
        RRNumber = socnumber.Trim(),
        RRSequenceNumber = i++
    }).AsEnumerable();
相关问题