c# - 使用 LINQ 在类中查找对象

标签 c# linq

我想退回具有我发送的配置文件 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/

相关文章:

c# - 将值从标签放入 excel 列的简短或简单的解决方案

c# - 使用递归异步/等待的异常处理

c# - Entity Framework 异常: Schema specified is not valid.

c# - LINQ 左外部联接 - 对象引用未设置为对象的实例

c# - 嵌套的 foreaches 到链式 linq 表达式中

c# - 获取 ASP.NET MVC 4 中按名称给定的方法的属性

c# - 是否可以为 UWP 项目使用新的 SDK 样式的 .csproj 文件?

c# - Linq - 比较字段的音译值

c# - 确保 IQueryable<T>.Where() 运行 SQL 查询而不是在内存中过滤

c# - 使用不同名称的 LINQ to Entities 表前 100