[英]Querying a Dictionary with a Lambda Expression
我在下面创建了一些示例代码,并尝试使用lambda表达式来查询SoftwareComponents字典。 问题是查询返回类型为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;
}
}
尝试这个:
var components = (from s in software.SoftwareComponents.Values
select new
{
Name = s.ComponentName,
Description = s.ComponentDescription
})
.ToList().GroupBy(s=>s.Name);
根据您提供的示例数据,按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等。唯一可直接选择的值是键(可以是复合的,因此具有多个值) 。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.