C# 嵌套DTO搜索
我向苏亚奇提交了以下数据清单:C# 嵌套DTO搜索,c#,linq,C#,Linq,我向苏亚奇提交了以下数据清单: 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 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,例如类test有一个类test2的成员,类test2有一个类test3类型的成员,每个类都有自己的唯一键,这个键不能在任何类中重复,比如GUid。
我想查询类Test,以找到其中一个具有给定唯一键的嵌套DTO。假设
tests
对象是IEnumerable
,这是一组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;
}
假设
tests
对象是IEnumerable
,这是一组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;
}
答案可能是使用以下形式:如果在基类上创建
FindKey
方法,并在派生类上相应地实现它,则可以简化查询:
//given:
//'tests' is a IEnumerable<UKey>
//'g' = a guid you are looking for
tests.SingleOrDefault(q => q.FindKey(g));
答案可能是使用以下形式:如果在基类上创建
FindKey
方法,并在派生类上相应地实现它,则可以简化查询:
//given:
//'tests' is a IEnumerable<UKey>
//'g' = a guid you are looking for
tests.SingleOrDefault(q => q.FindKey(g));