我已在线搜索此代码以合并多个列表并返回一个。如果所有属性都是字符串,则代码有效,但如果某些属性为double,则会出现错误。这个错误是“运营商'??'不能应用于'double'和'double'类型的操作数。任何帮助是极大的赞赏。谢谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication11
{
class Program
{
static void Main(string[] args)
{
List<Project> lst1; List<Project> lst2; List<Project> lst3;
lst1 = new List<Project>
{
new Project { ProjectId = 1, ProjectName = "P1" },
new Project { ProjectId = 2, ProjectName = "P2" },
new Project { ProjectId = 3, ProjectName = "P3" }
};
lst2 = new List<Project>
{
new Project { ProjectId = 1, CustomerNum = 1},
new Project { ProjectId = 2, CustomerNum = 2},
new Project { ProjectId = 3, CustomerNum = 3}
};
lst3 = new List<Project>
{
new Project { ProjectId = 1, Address = 10},
new Project { ProjectId = 2, Address = 20},
new Project { ProjectId = 3, Address = 30}
};
List<Project> lst = lst1.Union(lst2).Union(lst3).ToLookup(x => x.ProjectId).Select(x => new Project()
{
ProjectId = x.Key,
ProjectName = x.Select(y => y.ProjectName).Aggregate((z1, z2) => z1 ?? z2),
CustomerNum = x.Select(y => y.CustomerNum).Aggregate((z1, z2) => z1 ?? z2),
Address = x.Select(y => y.Address).Aggregate((z1, z2) => z1 ?? z2)
}).ToList();
foreach (var item in lst)
{
Console.WriteLine("{0}, {1}, {2}, {3}", item.ProjectId, item.ProjectName, item.CustomerNum, item.Address);
}
}
}
public class Project
{
public int ProjectId { get; set; }
public string ProjectName { get; set; }
public double CustomerNum { get; set; }
public double Address { get; set; }
}
}
答案 0 :(得分:1)
Null-coalescing对左侧的非可空类型(double
)不起作用
?? operator被称为null-coalescing运算符,用于为可空值类型或引用类型定义默认值
所以,您可以使用double?
(Nullable<double>
),这样可行。但是,正如所写,左手边总会有一个值,因此你的问题。 Alternatively, you could check if the type is a value type?
答案 1 :(得分:1)
如果您希望代码执行与其他类型相同的操作,则可以执行以下操作
CustomerNum = x.Select(y => y.CustomerNum).Aggregate((z1, z2) => z1)
答案 2 :(得分:0)
??用于说“如果左侧为空,则使用右侧的值”。由于Double是值类型,因此它永远不能为null。因此,您将始终只是到达酒店的左侧。编译器告诉你你的代码是可疑的。
使用Double?如果你想保留完全相同的代码。
答案 3 :(得分:0)
我提出了一个有效的简单(长)解决方案。这是合并列表的代码
List<Project> lst = new List<Project>();
for (int i = 0; i < lst1.Count; i++)
{
double cusnum = 0;
var lst2q = (from s in lst2
where s.ProjectId == lst1[i].ProjectId
select s).ToArray();
if (lst2q.Length > 0)
{
cusnum = lst2q[0].CustomerNum;
}
var lst3q = (from s in lst3
where s.ProjectId == lst1[i].ProjectId
select s).ToArray();
double cusadd = 0;
if (lst3q.Length > 0)
{
cusadd = lst3q[0].Address;
}
lst.Add(new Project
{
ProjectId = lst1[i].ProjectId,
ProjectName = lst1[i].ProjectName,
CustomerNum = cusnum,
Address = cusadd,
});
}