gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:27:05 25 4
gpt4 key购买 nike

我在下面创建了一些示例代码,并尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com