Querying a Dictionary with a Lambda Expression
我在下面创建了一些示例代码,并尝试使用lambda表达式来查询SoftwareComponents字典。问题是,当我需要进一步细化查询时,查询返回一个igrouping类型的var,以便返回一种igrouping类型,其中第一个字符串是softwarecomponent.componentname,第二个字符串是softwarecomponent.componentdescription。有人知道怎么做吗?
我希望返回的数据看起来像:"新类型说明""组件1""组件2""旧类型说明""组件3""组件4"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 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; } } |
试试这个:
1 2 3 4 5 6 7 | var components = (from s in software.SoftwareComponents.Values select new { Name = s.ComponentName, Description = s.ComponentDescription }) .ToList().GroupBy(s=>s.Name); |
根据您提供的示例数据,按componentname分组不会产生任何有用的组。我不确定您的数据是否对每个组件都有一个唯一的名称,但是如果有,那么分组实际上不会提供任何值。
但是,要实际实现所需的分组,可以执行以下操作:
1 2 3 | 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枚举组件。请注意,从组中检索值的唯一方法是选择第一个或最后一个条目,或者执行聚合和、平均值等。唯一可直接选择的值是键(它可能是复合的,因此具有多个值)。