class Supplier
{
public string Name { get; set; }
public string District { get; set; }
}
class Buyer
{
public string Name { get; set; }
public string District { get; set; }
}
List<Buyer> buyers = new List<Buyer>()
{
new Buyer() { Name = "Johny", District = "Fantasy District" },
new Buyer() { Name = "Peter", District = "Scientists District" },
new Buyer() { Name = "Paul", District = "Fantasy District" },
new Buyer() { Name = "Maria", District = "Scientists District" },
new Buyer() { Name = "Joshua", District = "EarthIsFlat District" },
new Buyer() { Name = "Sylvia", District = "Developers District" },
new Buyer() { Name = "Rebecca", District = "Scientists District" },
new Buyer() { Name = "Jaime", District = "Developers District" },
new Buyer() { Name = "Pierce", District = "Fantasy District" }
};
List<Supplier> suppliers = new List<Supplier>()
{
new Supplier() { Name = "Harrison", District = "Fantasy District" },
new Supplier() { Name = "Charles", District = "Developers District" },
new Supplier() { Name = "Hailee", District = "Scientists District" },
new Supplier() { Name = "Taylor", District = "EarthIsFlat District" }
};
首先:
var suppliersAndBuyers = from s in suppliers
orderby s.District
join b in buyers on s.District equals b.District into buyersGroup
select buyersGroup.DefaultIfEmpty(
new Buyer()
{
Name = string.Empty,
District = s.District
});
foreach (var item in suppliersAndBuyers)
{
foreach (var buyer in item)
{
Console.WriteLine($"{buyer.District} {buyer.Name}");
}
}
第二种方法:
var suppliersAndBuyers = from s in suppliers
orderby s.District
join b in buyers on s.District equals b.District into buyersGroup
from bG in buyersGroup.DefaultIfEmpty()
select new
{
Name = bG.Name == null ? string.Empty : bG.Name,
s.District,
};
foreach (var item in suppliersAndBuyers)
{
Console.WriteLine($"{item.District} {item.Name}");
}
这两种方法都可以产生完全相同的输出结果,它们之间唯一的区别是输出结果的方式吗?我应该使用哪一个?
编辑:第一种方法返回IEnumerable<IEnumerable<Buyer>>
,而第二种方法返回IEnumerable<AnonymousType>
,这两种方法之间唯一有意义的区别是它们返回的类型不同吗?这是决定使用哪种方法的唯一因素吗,无论我想要一个类型还是匿名类型?
Name = bG.Name == null ? string.Empty : bG.Name
->Name = bG.Name ?? ""
。 - ErikE