我有以下查询:
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);
答案 0 :(得分:31)
如果您需要将任何IEnumerable元素集合添加到列表中,则需要使用AddRange
。
vendlist.AddRange(vnlist);
答案 1 :(得分:6)
或者将它们结合起来......
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());
答案 2 :(得分:3)
我认为您尝试添加完整列表而不是单个CheckItems实例。 我这里没有C#编译器,但可能是AddRange而不是Add works:
vendlist.AddRange(vnlist);
答案 3 :(得分:0)
以下是一种简单的方法:
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);
}