A dictionary where value is an anonymous type in C#

前端 未结 5 539
鱼传尺愫
鱼传尺愫 2020-12-01 04:26

Is it possible in C# to create a System.Collections.Generic.Dictionary where TKey is unconditioned class and TValue

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 04:48

    You can't declare such a dictionary type directly (there are kludges but these are for entertainment and novelty purposes only), but if your data is coming from an IEnumerable or IQueryable source, you can get one using the LINQ ToDictionary() operator and projecting out the required key and (anonymously typed) value from the sequence elements:

    var intToAnon = sourceSequence.ToDictionary(
        e => e.Id,
        e => new { e.Column, e.Localized });
    

提交回复
热议问题