如何用LINQ筛选并按LayerName排序含内部Diagram列表的Element集合
Answer
Yes, this is totally feasible, and it’s straightforward to implement with LINQ once you’ve got your filtered collection. Here’s how to adjust your code to sort the results by the LayerName of the specific "Diagram1" entry:
How it works
- Keep your existing filter logic: You already have the code to narrow down
ElementBaseobjects that contain at least one Diagram named "Diagram1"—we’ll build on that. - Target the specific Diagram: For each filtered
ElementBase, we’ll fetch the exact Diagram with the name "Diagram1" (since your filter guarantees this exists, we can safely useFirst()here). - Sort by LayerName: Use LINQ’s
OrderBy()method to sort the filtered list based on theLayerNameproperty of that Diagram.
Updated C# Code Example
// Your existing filtered collection (adjust variable names to match your code) var filteredElements = elementList .Where(element => element.DiagramListe.Any(diagram => diagram.Name == "Diagram1")); // Sort the filtered elements by the LayerName of "Diagram1" var sortedFilteredElements = filteredElements .OrderBy(element => element.DiagramListe.First(diagram => diagram.Name == "Diagram1").LayerName) .ToList();
Quick Notes
- If there’s a chance multiple Diagrams in one
ElementBaseshare the name "Diagram1", you might want to useFirstOrDefault()instead ofFirst()(add a null check just in case), but since your filter already ensures at least one exists,First()is safe here. - For descending order, swap
OrderBy()withOrderByDescending(). - Ensure
LayerNameis a public (or accessible) property—LINQ can sort strings, numbers, and other comparable types out of the box.
Content of the question originates from Stack Exchange, question author Steffen_dd
相关产品推荐
相关产品推荐

