我有一个ELementList,每个元素都有一个带有几个图表的diagrammList。
我想在其diagrammList中选择所有带有searchname图表的元素。 (这是有效的)但我想通过图层名对这些列表进行排序。
这是一种方法吗?
谢谢Steffen
namespace ConsoleLinq
{
using System.Collections.ObjectModel;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Collection<ElementBase> ELementList = new Collection<ElementBase>();
ElementBase elementObjekt = new ElementBase { Name = "Node1" };
elementObjekt.DiagramListe.Add(new Diagram { Name = "Diagram1", LayerName = "Layer2" });
elementObjekt.DiagramListe.Add(new Diagram { Name = "Diagram2", LayerName = "Layer1" });
ELementList.Add(elementObjekt);
elementObjekt = new ElementBase { Name = "Node2" };
elementObjekt.DiagramListe.Add(new Diagram { Name = "Diagram1", LayerName = "Layer1" });
ELementList.Add(elementObjekt);
elementObjekt = new ElementBase { Name = "Node3" };
elementObjekt.DiagramListe.Add(new Diagram { Name = "Diagram2", LayerName = "Layer1" });
ELementList.Add(elementObjekt);
// is there a way to select any item in ELementList wich are "Diagram1" and sort the items by LayerName?
var searchList = (from item in ELementList
where item.DiagramListe.GetDiagram("Diagram1") != null
select item).ToList();
// output should
// searchList[0].Name = "Node2";
// searchList[1].Name = "Node1";
foreach (var item in searchList) item.DoSomething();
}
}
public class ElementBase
{
public string Name { get; set; }
public DiagramListe DiagramListe = new DiagramListe();
public void DoSomething() { }
}
public class DiagramListe : Collection<Diagram>
{
public Diagram GetDiagram(string diagramName)
=> (from obj in this
where obj.Name == diagramName
select obj).FirstOrDefault();
}
public class Diagram
{
public string Name { get; set; }
public string LayerName { get; set; }
}
}
答案 0 :(得分:1)
除了Select
之外,您还可以LayerName
加入一个也包含ElementBase
的匿名对象,然后使用OrderBy
按LayerName
对这些匿名对象进行排序然后Select
再次从匿名对象中取出ElementBase
。
var diagramNameSearchInput = "Diagram1"
var searchList =
( from item in ELementList
// put diagram into a variable so we call GetDiagram() only once per element
let matchingDiagram = item.DiagramListe.GetDiagram(diagramNameSearchInput)
where matchingDiagram != null
select new { // create anonymous object with all properties we need
BaseItem = item,
LayerName = matchingDiagram.LayerName
}
)
.OrderBy(a => a.LayerName) // sort anonymous objects
.Select(a => a.BaseItem) // result list will contain ElementBase elements
.ToList();
C# Fiddle这个例子。