You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

  1. Keep your existing filter logic: You already have the code to narrow down ElementBase objects that contain at least one Diagram named "Diagram1"—we’ll build on that.
  2. 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 use First() here).
  3. Sort by LayerName: Use LINQ’s OrderBy() method to sort the filtered list based on the LayerName property 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 ElementBase share the name "Diagram1", you might want to use FirstOrDefault() instead of First() (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() with OrderByDescending().
  • Ensure LayerName is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:37:14