使用LINQ在类中查找对象

DaI*_*mTo 4 c# linq

我想返回具有我发送的配置文件ID的项目.所以为了做到这一点,我需要遍历所有的项目 - > WebProproperties - > profile.类结构在问题的最后.

我宁愿使用LINQ而不是创建嵌套foreach.我一直试图让这个工作超过一个小时.我被卡住了.

我的第一个想法是简单地使用where.但这不起作用,因为你需要在另一方需要相同的东西.

this.Accounts.items.Where(a => a.webProperties.Where(b => b.profiles.Where(c => c.id == pSearchString)) ).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

我的第二个想法是尝试使用Exists我没有太多经验:

Item test =  from item in this.Accounts.items.Exists(a => a.webProperties.Exists(b => b.profiles.Exists(c => c.id == pSearchString))) select item;
Run Code Online (Sandbox Code Playgroud)

这也不起作用:

找不到源类型'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; }
    }
Run Code Online (Sandbox Code Playgroud)

Stu*_*tLC 6

您可以Any()用来确定存在.另请注意,许多扩展方法都具有带谓词的重载,包括FirstOrDefault():

this.Accounts.items.FirstOrDefault(a => a.webProperties
      .Any(b => b.profiles
          .Any(c => c.id == pSearchString)));
Run Code Online (Sandbox Code Playgroud)