【问题标题】:C# Lambda multiple criteria, child ListC# Lambda 多个条件,子列表
【发布时间】:2011-06-26 03:08:46
【问题描述】:

想知道以下是否可行,但我仍然对 lambda 表达式有所了解。

    GetAll(x => x.Username.ToUpper().Contains(SEARCH) 
             && x.AddressList.Type_ID == 98.ToList();

这段代码的问题在于“地址”是一个列表。本质上,我们希望在 1) 对 UserName 执行搜索和 2) 匹配子列表的属性之后返回 List。

从语义上讲,上面的代码不起作用,因为 AddressList 是一个列表,而不是单个实体,因此“Type_ID”不能用作选择。

这可以实现吗?

【问题讨论】:

  • 地址包含地址列表什么..它的类型是什么..它是否有Type_ID属性..请提供更多代码。

标签: c# list lambda filter


【解决方案1】:

你的意思是类似的吗?

GetAll(x => x.Username.ToUpper().Contains(SEARCH) 
             && x.AddressList.Any(e => e.Type_ID == 98));

【讨论】:

    【解决方案2】:

    有对列表进行操作的扩展方法,但仍然不清楚您要做什么。您想要地址列表中 any 项的 Type_ID 为 98 的结果吗?如果是这样,请使用 Any 函数。如果列表中的所有地址都必须具有该类型 ID,则使用 All。下面是一些示例代码:

    class Address
    {
       public int Type_ID { get; set; }
       public Address(int Type_ID)
       {
          this.Type_ID = Type_ID;
       }
    }
    
    class Entry
    {
       public List<Address> AddressList { get; set; }
       public string UserName { get; set; }
       public Entry(string name, List<Address> addresses)
       {
          AddressList = addresses;
          this.UserName = name;
       }
    }
    
    class EntryList
    {
       private List<Entry> entries;
    
       public IEnumerable<Entry> GetAll(Func<Entry, bool> filter)
       {
          return entries.Where(filter).ToArray();
       }
    
       public EntryList(List<Entry> entries)
       {
          this.entries = entries;
       }
    }
    
    static void Main(string[] args)
    {
    
       EntryList e1 = new EntryList(new List<Entry>()
          {new Entry("Fred with 1 98 address", new List<Address> { new Address(97), new Address(98) }),
             new Entry("Bob with no 98 address", new List<Address> { new Address(96), new Address(97) }),
             new Entry("Jerry with all 98 addresses", new List<Address> { new Address(98), new Address(98) })});
    
       var all98 = e1.GetAll(x => x.AddressList.All(y => y.Type_ID == 98));
       var any98 = e1.GetAll(x => x.AddressList.Any(y => y.Type_ID == 98));
    
       Console.WriteLine("Results for ALL:");
       foreach (var e in all98)
          Console.WriteLine(e.UserName);
       Console.WriteLine("Results for ANY:");
       foreach (var e in any98)
          Console.WriteLine(e.UserName);
    }
    

    输出是:

    Results for ALL:
    Jerry with all 98 addresses
    Results for ANY:
    Fred with 1 98 address
    Jerry with all 98 addresses
    

    【讨论】:

    • 我不明白为什么这被否决了......请在投反对票时发表评论,以便我们知道问题所在。这个答案付出了很多努力。
    猜你喜欢
    • 1970-01-01
    • 2013-07-21
    • 2016-11-16
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 2020-11-03
    相关资源
    最近更新 更多