使用Lambda表达式查询字典

时间:2009-06-18 15:39:16

标签: c# dictionary lambda

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

我希望返回的数据看起来像: “新类型说明”   “COMPONENT1”   “COMPONENT2” “旧类型描述”   “component3”   “component4”

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;
    }
}

2 个答案:

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分:1)

根据您提供的示例数据,按ComponentName分组不会产生任何有用的组。我不确定您的数据是否确实具有每个组件的唯一名称,但如果有,则分组实际上不会提供任何值。

但是,要实际实现所需的分组,您可以执行以下操作:

var components = from v in software.SoftwareComponents.Values
                 group v by v.name into g
                 select new { ComponentName = g.Key, Description = g.First(v => v.Description);

这应该导致使用ComponentName和Description枚举组件。请注意,从组中检索值的唯一方法是选择第一个或最后一个条目,或执行总和,avg等。唯一可直接选择的值是键(可以是复合的,因此具有多个值) 。)