【问题标题】:Nested DTO search嵌套 DTO 搜索
【发布时间】:2013-01-24 17:03:41
【问题描述】:

我有 DTO Suach 的列表:

 Public Class UKey
{
    public Int64 Key{ get; set; }

}

Public Class Test : UKey
{
    public Int64? CityId  { get; set; }
    public Test2  test2{ get; set; }
}
Public Class Test2 : UKey
{
    public Int64? CountryId { get; set; }
    public Test3 test3 {get;set;}
}
public Class Test3 :UKey
{

}

我有嵌套的 DTO,例如 class test 有一个 class test 2 的成员, class test2 有一个 type class test 3 的成员,每个类都有自己的唯一键,这个键不能在任何一个中重复,类似于 GUId 的东西。 我想查询 Class Test 以找到具有给定唯一键的嵌套 Dto 之一。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    假设tests对象为IEnumerable<Test>,即Test对象的集合;

    tests.SingleOrDefault(q => q.test2.Key == id || q.test2.test3.Key == id);
    

    更新:您需要应用递归搜索。我稍微改变了基类;

    public class UKey
    {
        public Int64 Key { get; set; }
        public UKey ReferencedEntity { get; set; }
    }
    

    以及搜索功能:

    private UKey Search(UKey entity, Int64 id)
        {
            UKey result = null;
            if (entity.Key == id)
                result = entity;
            else
            {
                result = this.Search(entity.ReferencedEntity,id);
            }
            return result;
        }
    

    【讨论】:

      【解决方案2】:

      答案可能是使用recursion 的形式:如果您在基类上创建FindKey 方法并在派生类上相应地实现它,则可以简化查询:

      //given: 
      //'tests' is a IEnumerable<UKey>
      //'g' = a guid you are looking for
      tests.SingleOrDefault(q => q.FindKey(g));
      

      类实现可能如下所示:

      public abstract class UKey
      {              
          public Guid Key{ get; set; }
          public abstract bool FindKey(Guid g);
      }
      
      public class Test : UKey
      {
          public Int64? CityId  { get; set; }
          public Test2  Test2{ get; set; }
      
          public override bool FindKey(Guid g){
              return Key == g || (Test2!= null && Test2.FindKey(g));
          }   
      }
      
      /*etc.. implement the FindKey method on all you derived classes*/
      

      【讨论】:

        猜你喜欢
        • 2011-09-25
        • 2023-03-20
        • 1970-01-01
        • 2019-12-17
        • 2011-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多