我正在编写一个LINQ查询,它在两个表,艺术家和组(音乐组)上执行连接。查询正在检查属于特定组的艺术家,并将其作为列表返回,我将遍历并打印到控制台。
问题在于我被迫与我的if一起写了一个else语句并返回一些东西。我当前正在返回null,但是当我打印出我的列表时,想要完全跳过该步骤,因为空值显示(作为空值)。我尝试过使用.Distinct()
方法,但仍然会在列表中留下一个null。
var Beatles = Artists.Join(
Groups,
artist => artist.GroupId,
group => group.Id,
(artist, group) =>
{
if(artist.GroupId == 1)
{
return artist.ArtistName;
}
else{
return ;
}
})
.ToList()
.Distinct();
if(Beatles.Any())
{
System.Console.WriteLine("Here are all the members of the Beatles");
foreach(var person in Beatles)
{
System.Console.WriteLine(person);
}
};
答案 0 :(得分:3)
您只需使用Where
进行过滤即可。
var Beatles =
(from a in Artists
join g in Groups on a.GroupId equals g.Id
where a.GroupId == 1
select a.ArtistName).ToList();
我无法弄清楚你为什么申请加入,在这种情况下完全是多余的。
var Beatles = Artists.Where(x => x.GroupId == 1).Select(x => x.ArtistName).ToList();
我试过使用.Distinct()方法,但它仍会留下一个 在我的列表中为null。
我认为您使用Distinct
是因为过滤了null
值。但这不是Distinct
的目的。这完全是错误的。