c# - 将字典转换为列表<struct>

标签 c# linq

我有一个专门为用户控件创建的结构。我的想法是我将拥有公共(public)属性(property) Guid Dictionary<string, Guid> Attachments然后将其转换为我的私有(private) List<Attachment> attachments在二传手上。我在这样做时遇到了麻烦,最好是使用 linq,但我对替代方案持开放态度。谢谢...

private List<Attachment> attachments;
public struct Attachment
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}
public Dictionary<string, Guid> Attachments
{
    get { return attachments.ToDictionary(a => a.Name, a => a.Id); }
    set { attachments = new List<Attachment> // not sure what to do here }
}

最佳答案

假设这是一个有效的设计(我还没有真正考虑过)我怀疑你想要:

attachments = value.Select(pair => new Attachment { Id = pair.Value,
                                                    Name = pair.Key })
                   .ToList();

不过,我强烈建议您不要使用可变结构。使用结构本身并不算太糟糕,但我会将其更改为:
public struct Attachment
{
    private readonly Guid id;
    private readonly String name;

    public Guid Id { get { return id; } }
    public string Name { get { return name; } }

    public Attachment(Guid id, string name)
    {
        this.id = id;
        this.name = name;
    }
}

...此时转换只是:
attachments = value.Select(pair => new Attachment(pair.Value, pair.Key))
                   .ToList();

关于c# - 将字典转换为列表<struct>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9019362/

相关文章:

c# - 如何对 SHA-256 哈希进行十六进制编码

C# 和 Java : 3/2 * 3. 2 = 3.2,为什么?

c# - 使用 LINQ 对备用对进行分组

c# - 如何在对另一个属性求和的同时聚合一个属性?

c# - WPF 使用数据库处理点击事件

c# - 将列表保存到 txt 文件

c# - 返回 bool 值和字符串值的最佳做法是什么

c# - 批量插入的 LINQ-to-SQL 性能问题

c# - NHibernate 高效删除使用 LINQ Where 条件

.net - LINQ 查询将数据插入数据库