在以下关于LINQ Outer Join的MSDN官方文章中,作者在...select new { person.FirstName, PetName = subpet?.Name ?? String.Empty };
中一起使用?和??。 问题:为什么不将??
用作:select new { person.FirstName, PetName = subpet.Name ?? String.Empty };
,我认为这会转换为if subpet.Name is null give me empty string
。我误解了什么吗?
查询原因:当我在代码中使用?
和??
时(解释为here)VS2015
智能感知是给我这个错误也在那篇文章中解释过。
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Pet
{
public string Name { get; set; }
public Person Owner { get; set; }
}
public static void LeftOuterJoinExample()
{
Person magnus = new Person { FirstName = "Magnus", LastName = "Hedlund" };
Person terry = new Person { FirstName = "Terry", LastName = "Adams" };
Person charlotte = new Person { FirstName = "Charlotte", LastName = "Weiss" };
Person arlene = new Person { FirstName = "Arlene", LastName = "Huff" };
Pet barley = new Pet { Name = "Barley", Owner = terry };
Pet boots = new Pet { Name = "Boots", Owner = terry };
Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
Pet bluemoon = new Pet { Name = "Blue Moon", Owner = terry };
Pet daisy = new Pet { Name = "Daisy", Owner = magnus };
// Create two lists.
List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy };
var query = from person in people
join pet in pets on person equals pet.Owner into gj
from subpet in gj.DefaultIfEmpty()
select new { person.FirstName, PetName = subpet?.Name ?? String.Empty };
foreach (var v in query)
{
Console.WriteLine($"{v.FirstName+":",-15}{v.PetName}");
}
}
// This code produces the following output:
//
// Magnus: Daisy
// Terry: Barley
// Terry: Boots
// Terry: Blue Moon
// Charlotte: Whiskers
// Arlene:
答案 0 :(得分:1)
你不是误会。由于DefaultIfEmpty()
,程序员正在测试subpet
为null
在表达式
中 subpet?.Name ?? String.Empty
subpet
可以为null,在这种情况下subpet?.Name
也为空。String.Empty
可缩短为&#34;&#34; 所以要确保非空字符串,
subpet?.Name ?? ""
答案 1 :(得分:0)
如@Lee所述,<Fraction?>
可能为空。因此,在调用subpet
时抛出异常.Hence,subpet.Name
检查??
是否为空,subpet
返回调用?
属性。< / p>