我想退回具有我发送的配置文件 ID 的项目。因此,为了做到这一点,我需要遍历所有项目 -> WebProperties -> 配置文件。类结构在问题的末尾。
我宁愿使用 LINQ 而不是创建嵌套的 foreach
。我一直在努力让它工作一个多小时。我卡住了。
我的第一个想法是简单地使用where
。但这是行不通的,因为你需要在另一边有一些东西需要相等。
this.Accounts.items.Where(a => a.webProperties.Where(b => b.profiles.Where(c => c.id == pSearchString)) ).FirstOrDefault();
我的第二个想法是尝试使用 Exists
,我没有太多经验:
Item test = from item in this.Accounts.items.Exists(a => a.webProperties.Exists(b => b.profiles.Exists(c => c.id == pSearchString))) select item;
这也行不通:
Could not find an implementation of query pattern for source type 'Bool'
public RootObject Accounts {get; set;}
public class RootObject
{
public string kind { get; set; }
public string username { get; set; }
public int totalResults { get; set; }
public int startIndex { get; set; }
public int itemsPerPage { get; set; }
public List<Item> items { get; set; }
}
public class Profile
{
public string kind { get; set; }
public string id { get; set; }
public string name { get; set; }
public string type { get; set; }
}
public class WebProperty
{
public string kind { get; set; }
public string id { get; set; }
public string name { get; set; }
public string internalWebPropertyId { get; set; }
public string level { get; set; }
public string websiteUrl { get; set; }
public List<Profile> profiles { get; set; }
}
public class Item
{
public string id { get; set; }
public string kind { get; set; }
public string name { get; set; }
public List<WebProperty> webProperties { get; set; }
}
最佳答案
您可以使用 Any()
来确定存在。另外,请注意,许多扩展方法都有采用谓词的重载,包括 FirstOrDefault()
:
this.Accounts.items.FirstOrDefault(a => a.webProperties
.Any(b => b.profiles
.Any(c => c.id == pSearchString)));
关于c# - 使用 LINQ 在类中查找对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23425869/