将字典转换为列表<struct> </struct>

时间:2012-01-26 14:13:36

标签: c# linq

我有一个我为usercontrol特定创建的结构。我的想法是,我将拥有一个公共财产Guid Dictionary<string, Guid> Attachments,然后将其转换为我在设置者上的私人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 }
}

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:3)

我想你想要:

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