C# 从 linq var 将项目添加到列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9216207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add items to list from linq var
提问by Nate Pet
I have the following query:
我有以下查询:
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();
// Next, when I try to add vnlist to vendlist, I get an error as I cannot add this to the list I get and error saying I have some invalid arguments
// 接下来,当我尝试将 vnlist 添加到 vendlist 时,我收到一个错误,因为我无法将其添加到我得到的列表中,并且错误提示我有一些无效的参数
vendlist.Add(vnlist);
采纳答案by Samich
回答by Michel Keijzers
I think you try to add a complete list instead of a single CheckItems instance. I don't have a C# compiler here but maybe AddRange instead of Add works:
我认为您尝试添加一个完整的列表而不是单个 CheckItems 实例。我这里没有 C# 编译器,但也许 AddRange 而不是 Add 有效:
vendlist.AddRange(vnlist);
回答by CrazyDart
Or combine them...
或者把它们结合起来...
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());
回答by Talha Imam
Here's one simple way to do this:
这是执行此操作的一种简单方法:
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);
}

