获取所选可枚举项的索引

时间:2017-04-12 08:21:34

标签: c# lambda

public IEnumerable<InvalidSimContract> ValidateSims(SimSearchCriteriaContract searchCriteria)
        {
            var retval = new List<InvalidSimContract>();
            VZWSuspendLogic obj = new VZWSuspendLogic();
             var allowedSuspendDaysExpiredSims = searchCriteria.UserInputSims
                .Where(s => obj.HasExpiredAllowedSuspendDays(s.SimId, searchCriteria.ServiceTypeId, searchCriteria.ToState.Id))
                .Select(s => s.SimNumber).ToList();

            if (allowedSuspendDaysExpiredSims != null)
            {
                return allowedSuspendDaysExpiredSims.Select((s, i) =>
                new InvalidSimContract
                {
                    Message = String.Format("Line {0} contains SIM Number :{1} has expired the maximum allowed suspension days for this year. Allowed suspension days for the year is {2} days.", i + 1,s, _allowedSuspendDaysInLast12Months),
                    UserInput = s,
                    ImeiNumber = string.Empty,
                    LineNumber = i + 1
                }
            ).ToList();
            }

            return retval;
        }

我想将过滤项目的索引号打印为行号。那么如何过滤所选项目的索引号。

1 个答案:

答案 0 :(得分:2)

您需要在执行i之前添加.Where()(索引)

var allowedSuspendDaysExpiredSims = searchCriteria.UserInputSims
    .Select((s, i) => new
    {
        Obj = s,
        Ix = i,
    })
    .Where(s => obj.HasExpiredAllowedSuspendDays(s.Obj.SimId, searchCriteria.ServiceTypeId, searchCriteria.ToState.Id))
    .Select(s => new
    {
        s.Obj.SimNumber,
        s.Ix,
    }).ToList();

if (allowedSuspendDaysExpiredSims != null)
{
    return allowedSuspendDaysExpiredSims.Select(s =>
    new InvalidSimContract
    {
        Message = String.Format("Line {0} contains SIM Number :{1} has expired the maximum allowed suspension days for this year. Allowed suspension days for the year is {2} days.", s.Ix + 1, s.SimNumber, _allowedSuspendDaysInLast12Months),
        UserInput = s.SimNumber,
        ImeiNumber = string.Empty,
        LineNumber = s.Ix + 1
    }
    ).ToList();
}