从linqvar将项目添加到列表中

本文关键字:列表 添加 项目 linqvar | 更新日期: 2023-09-27 18:23:52

我有以下查询:

    public class CheckItems
    {
        public String Description { get; set; }
        public String ActualDate { get; set; }
        public String TargetDate { get; set; }
        public String Value { get; set; }
    }

   List<CheckItems>  vendlist = new List<CheckItems>();
   var vnlist = (from up in spcall
               where up.Caption == "Contacted"
                      select new CheckItems
                      {
                          Description = up.Caption,
                          TargetDate = string.Format("{0:MM/dd/yyyy}", up.TargetDate),
                          ActualDate = string.Format("{0:MM/dd/yyyy}", up.ActualDate),
                          Value = up.Value
                      }).ToList();

//接下来,当我试图将vnlist添加到vendlist时,我遇到了一个错误,因为我无法将其添加到我得到的列表中,并且错误地说我有一些无效的参数

         vendlist.Add(vnlist);

从linqvar将项目添加到列表中

如果需要向列表中添加任何IEnumerable元素集合,则需要使用AddRange

vendlist.AddRange(vnlist);

或者将它们组合。。。

vendlist.AddRange((from up in spcall
               where up.Caption == "Contacted"
                      select new CheckItems
                      {
                          Description = up.Caption,
                          TargetDate = string.Format("{0:MM/dd/yyyy}", up.TargetDate),
                          ActualDate = string.Format("{0:MM/dd/yyyy}", up.ActualDate),
                          Value = up.Value
                      }).ToList());

我认为您应该尝试添加一个完整的列表,而不是单个CheckItems实例。我这里没有C#编译器,但可能是AddRange而不是Addworks:

vendlist.AddRange(vnlist);

这里有一个简单的方法:

List<CheckItems>  vendlist = new List<CheckItems>();
var vnlist =    from up in spcall
                where up.Caption == "Contacted"
                select new
                  {
                      up.Caption,
                      up.TargetDate,
                      up.ActualDate,
                      up.Value
                  };
foreach (var item in vnlist)
            {
                CheckItems temp = new CheckItems();
                temp.Description = item.Caption;
                temp.TargetDate = string.Format("{0:MM/dd/yyyy}", item.TargetDate);
                temp.ActualDate = string.Format("{0:MM/dd/yyyy}", item.ActualDate);
                temp.Value = item.Value;
                vendlist.Add(temp);
            }