从使用LINQ的另一个子项目列表中选择项目列表



这是一个新手问题:我有这两个类要获得特定列表。

 public class Customer
 {
     public string firstname { get; set; }
     public string lastname { get; set; }
     ObservableCollection<Address> { get; set; }
 }
 public class Address
 {
      public string Street { get; set; }
      public string City { get; set; }
 }

我有此测试数据:

乔,杜伊,纽约市Main St 123Jane,Doe,纽约市Main St 456
唐纳德(Donald),流浪汉,华盛顿特区宾夕法尼亚州1600号Spongebob,Squarepant,比基尼底部海岸街124号
奥斯卡(Oscar),The Grouch,芝麻街,任何城市
Milo,Murphy,Unlucky Street,Swamp City

我希望能够获取名字,姓氏,街和城市的所有详细信息,该城市是"纽约市"。

那么如何为此编写linq查询?

假设您希望所有具有"纽约市"地址的客户及其所有地址(层次结构),您只需这样做:

var query = from c in customers
            where c.addresses.Any(a => a.City == "New York City")
            select c;

如果您确实想要扁平的结果集,可以连接表并投影到匿名类型:

var query = from c in customers
            from a in c.addresses
            where a.City == "New York City"
            select new
            {
                c.firstname,
                c.lastname,
                a.City,
                a.Street
            };

最新更新