考虑到下面的情况,我需要获得属于分配给顶层的中间对象列表的所有底层级对象。我所拥有的结构意味着中层对象悬挂在顶层,但底层只是所有的集合。因此,即使列表不存在,我也需要获得有效“挂掉”顶层和中层的所有底层对象。在lambda中有一个很好的方法吗?
class Program
{
static void Main(string[] args)
{
List<TopClass> topClasses = new List<TopClass>();
List<MiddleClass> mcList1 = new List<MiddleClass>();
mcList1.Add(new MiddleClass(1));
mcList1.Add(new MiddleClass(3));
mcList1.Add(new MiddleClass(5));
TopClass tc1 = new TopClass(1, mcList1);
topClasses.Add(tc1);
List<MiddleClass> mcList2 = new List<MiddleClass>();
mcList2.Add(new MiddleClass(2));
mcList2.Add(new MiddleClass(4));
TopClass tc2 = new TopClass(2, mcList2);
topClasses.Add(tc2);
List<MiddleClass> mcList3 = new List<MiddleClass>();
mcList3.Add(new MiddleClass(6));
mcList3.Add(new MiddleClass(7));
TopClass tc3 = new TopClass(3, mcList3);
// ** Note not added to the global list
List<BottomClass> bottomClasses = new List<BottomClass>();
bottomClasses.Add(new BottomClass(10, 1));
bottomClasses.Add(new BottomClass(20, 2));
bottomClasses.Add(new BottomClass(30, 3));
bottomClasses.Add(new BottomClass(40, 4));
bottomClasses.Add(new BottomClass(50, 5));
bottomClasses.Add(new BottomClass(60, 6));
bottomClasses.Add(new BottomClass(70, 7));
bottomClass.FindAll(b => ....?
}
}
public class TopClass //Instruments
{
public int Id { get; set; }
public List<MiddleClass> MiddleClasses { get; set; }
public TopClass(int id, List<MiddleClass> middleClasses)
{
this.Id = id;
this.MiddleClasses = middleClasses;
}
}
public class MiddleClass // Sequences
{
public int Id { get; set; }
public MiddleClass(int id)
{
this.Id = id;
}
}
public class BottomClass //SequenceItem
{
public int Id { get; set; }
public int MiddleClassId { get; set; }
public BottomClass(int id, int middleClassId)
{
this.Id = id;
this.MiddleClassId = middleClassId;
}
}
结果将是一个包含10到50但不包含60和70的列表。
答案 0 :(得分:1)
怎么样
topClasses
.SelectMany(x=>x.MiddleClasses)
.SelectMany(x=>bottomClasses.Where(y=>y.MiddleClassId==x.Id))
可选择在末尾添加.Distinct()
以获得唯一性
或者从另一方面
bottomClasses.Where(
b=>topClasses.Any(t=>t.MiddleClasses.Any(m=>m.Id==b.MiddleClassId))
)
答案 1 :(得分:0)
不确定这是不是你想要的......
var test = bottomClasses.Where(b => b.Id >= 10 && b.Id <= 50);
如果没有,请评论我错误解释的内容:)
答案 2 :(得分:0)
这就是你想要的。所以给出一个TopClass,例如tc3,这将为你提供tc3
之外的所有底层课程 var allMiddleClasses = topClasses.SelectMany(t => t.MiddleClasses);
var allBC =
bottomClasses
.Where(b => allMiddleClasses.Select(m => m.Id).Contains(b.MiddleClassId))
.ToList();