将词典转换为列表<;struct>;

本文关键字:lt struct gt 列表 转换 | 更新日期: 2023-09-27 18:21:25

我有一个为用户控件创建的结构。我的想法是,我将拥有一个公共属性Guid Dictionary<string, Guid> Attachments,然后在setter上将其转换为我的私有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 }
}

将词典转换为列表<;struct>;

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

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();

我想你想要:

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