带连接的 linq 查询
我无法准备我需要的查询。我有代码:
public class Dog
{
public int id;
public int? OwnerID;
public string name;
}
public class Person
{
public int id;
public string Name;
}
public class Group
{
public Dog dog;
public Person owner;
}
class Program
{
static void Main(string[] args)
{
IEnumerable<Dog> dogs = new[] {
new Dog { id = 1, OwnerID = null, name = "Burke" },
new Dog { id = 2, OwnerID = 2, name = "Barkley" }
};
IEnumerable<Person> owners = new[] {
new Person { id = 1, Name = "Jack" },
new Person { id = 2, Name = "Philip" }
};
var groups = from dog in dogs
join owner in owners on dog.OwnerID equals owner.id
select new Group
{
dog = dogs.First(d => d.id == dog.id),
owner = owners.First(o => o.id == owner.id)
};
foreach (var g in groups)
{
var text = g.dog.name + " belongs to " + (g.owner == null ? "no one" : g.owner.Name);
Console.WriteLine(text);
}
Console.ReadLine();
}
}
但它没有按我的预期工作。如何准备查询,即使 Dog 对象中的 OwnerID 为 null,仍会创建 Group 的新实例并将其添加到 groups 变量中?
I cannot prepare a query that I need. I have code:
public class Dog
{
public int id;
public int? OwnerID;
public string name;
}
public class Person
{
public int id;
public string Name;
}
public class Group
{
public Dog dog;
public Person owner;
}
class Program
{
static void Main(string[] args)
{
IEnumerable<Dog> dogs = new[] {
new Dog { id = 1, OwnerID = null, name = "Burke" },
new Dog { id = 2, OwnerID = 2, name = "Barkley" }
};
IEnumerable<Person> owners = new[] {
new Person { id = 1, Name = "Jack" },
new Person { id = 2, Name = "Philip" }
};
var groups = from dog in dogs
join owner in owners on dog.OwnerID equals owner.id
select new Group
{
dog = dogs.First(d => d.id == dog.id),
owner = owners.First(o => o.id == owner.id)
};
foreach (var g in groups)
{
var text = g.dog.name + " belongs to " + (g.owner == null ? "no one" : g.owner.Name);
Console.WriteLine(text);
}
Console.ReadLine();
}
}
and it doesn't work as I expected. How do I prepare query that even if OwnerID in Dog object is null new instance of Group is still created and added to groups variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样
参见 http://smehrozalam.wordpress .com/2009/06/10/c-left-outer-joins-with-linq/
尽管他的示例显示了 SQL 的翻译,但这同样适用于 linq to object
Like So
See http://smehrozalam.wordpress.com/2009/06/10/c-left-outer-joins-with-linq/
Even though his examples show translation to SQL, the same applies for linq to objects
根据您的描述,听起来您想对 Dogs 进行左外连接查询。
查看 Microsoft LINQ 示例中的示例,了解如何使用
DefaultIfEmpty()
LINQ 函数。From what you are describing, it sounds like you want to do a Left Outer Join query on Dogs.
Check out this example from Microsoft's LINQ Examples on how to use the
DefaultIfEmpty()
LINQ Function.