无法循环并为数组添加第二个值

时间:2019-06-10 20:38:17

标签: c#

在下面的循环中,仅当存在多个值时,我想通过用“,”分隔来添加sr的第二个值。否则它必须显示sr值,且不带“,”。

                var size = 0;
                if (records != null)
                {
                    size = records.Length;
                }
                var srArray = new List<SRItem>();
                var i = 0;
                if (records == null) return Json(srArray);
                foreach (var item in records)
                {
                    foreach (var prr in item.Psr)
                    {
                        srArray.Add(new SRItem
                        {
                            name = pr.Name.lastName + "/" + pr.Name.firstName,
                            st= pr.Seat.seatNumber,
                            sr = pr.PSRList[0].SRCode                                
                        });

                    }
                    i++;
                }


                return Json(srArray.ToArray());
            }
            else
            {
                throw new Exception("Session no longer exists, Please refresh the whole page");
            }

2 个答案:

答案 0 :(得分:0)

var i的目的是什么?

您还正在创建prr并尝试使用pr在循环中访问它们。将prr更改为pr或pr更改为prr。

foreach (var prr in item.Psr) //< ---prr
{
    //in here you have pr
    srArray.Add(new SRItem
    {
        name = pr.Name.lastName + "/" + pr.Name.firstName,
        st= pr.Seat.seatNumber,
        sr = pr.PSRList[0].SRCode                                
    });
}

更改为:

foreach (var pr in item.Psr)
{
    srArray.Add(new SRItem
    {
        name = pr.Name.lastName + "/" + pr.Name.firstName,
        st= pr.Seat.seatNumber,
        sr = pr.PSRList[0].SRCode                                
    });
}

答案 1 :(得分:0)

如果我理解您的描述正确无误,您会想要

sr = string.Join(", ", pr.PSRList.Select(p => p.SRCode));