c# - 使用 Lambda 表达式查询字典

标签 c# dictionary lambda

我在下面创建了一些示例代码,并尝试使用 lambda 表达式来查询 SoftwareComponents 字典。问题是查询返回 IGrouping 类型的 var,而我需要做的是进一步细化查询,以便它返回 IGrouping 类型,其中第一个字符串是 SoftwareComponent.ComponentName,第二个字符串是 SoftwareComponent。组件说明。有人知道怎么做吗?

我希望返回的数据类似于: “新类型说明” “组件1” “组件2” “旧类型描述” “组件3” “组件4”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{

    protected void Page_Load(object sender, EventArgs e)
    {
        UnOwnedSoftware software = new UnOwnedSoftware();

        var components = software.SoftwareComponents.Values.
            GroupBy(s => s.ComponentName);
    }
}

public class UnOwnedSoftware
{
    public Dictionary<int, SoftwareComponent> SoftwareComponents
        = new Dictionary<int, SoftwareComponent>();

    public UnOwnedSoftware()
    {
        SoftwareComponent component1 = new SoftwareComponent
            ("component1", 1, "New Type Description");
        SoftwareComponent component2 = new SoftwareComponent
            ("component2", 2, "New Type Description");
        SoftwareComponent component3 = new SoftwareComponent
            ("component3", 3, "Old Type Description");
        SoftwareComponent component4 = new SoftwareComponent
            ("component4", 4, "Old Type Description");

        SoftwareComponents.Add(1, component1);
        SoftwareComponents.Add(2, component2);
        SoftwareComponents.Add(3, component3);
        SoftwareComponents.Add(4, component4);
    }   
}

public class SoftwareComponent
{
    public string ComponentName { get; set; }
    public int ID { get; set; }
    public string ComponentDescription { get; set; }

    public SoftwareComponent(string componentName, int id, string componentDescription)
    {
        ComponentName = componentName;
        ID = id;
        ComponentDescription = componentDescription;
    }
}

最佳答案

试试这个:

var components = (from s in software.SoftwareComponents.Values
                  select new
                  {
                      Name = s.ComponentName,
                      Description = s.ComponentDescription
                  })
                 .ToList().GroupBy(s=>s.Name);

关于c# - 使用 Lambda 表达式查询字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1013440/

相关文章:

c# - 如何从xml文件中读取单个节点值

c# - _ 在函数和变量名中是什么意思?

c# - 从解析的字符串构建多级数组数组/锯齿状数组

c# - 用于创建 PowerPoint 演示文稿的库

.net - 是否有 .NET 库或示例代码可用于优化线上的点或抽取?

c# - 访问成员表达式的值

ios - 尝试访问另一个类型为 "Dictionary<String, Double>"的变量中的实例变量时出错

Java HashMap 迭代 Map.Entry<> 与 Entry<>

c++ - 在对象 vector 上调用成员函数

c# - 为什么在 lambda 表达式中使用迭代变量不好