将列表映射到自定义词典

时间:2017-07-13 14:54:10

标签: c# linq

我正在开发一款我没有设计的应用,并且不会以这种方式设计它。我有一个列表要映射到Dictionary<string, object>。生成的字典应如下所示:

var dictionary = new Dictionary<string, object>{
{ CommonProperty.Name, item.Name },
{ CommonProperty.UriAddr, item.UriAddr}         
 //other properties                     
}

CommonProperty是一个具有静态属性的密封类,例如NameUriAddr等。我尝试过类似的事情: -

我试图利用下面的Linq查询而陷入困境:

var dict = myList.Select((h, i) => new { key = h, index = i })
.ToDictionary(o => o.key, o => values[o.index]));

和...

foreach(var item in list){
var _dict = new Dictionary<string, object>{
{CommonProperty.Name, item.Name},
//other properties
  }
}

CommonProperty会向该属性添加其他信息,因此必须进行调用。键和值都是相同的名称&#39;。

我的问题是:如何映射myList并返回上面的字典?还有更好的方法吗?

提前致谢。

2 个答案:

答案 0 :(得分:1)

你究竟是什么意思“关键和价值都是相同的'名字'”?如果您想要在项目中的键匹配项目中的属性名称,那么您可以使用反射,如下所示:

item.GetType().GetProperties().ToDictionary(x => x.Name, x => x.GetValue(item));

此示例不会通过CommonProperty进行过滤,如果项目具有您不感兴趣的任何属性,则可能会导致字典中的额外条目。

以下是完整的示例程序,它显示目录中所有文件的属性:

static class Program
{
    static Dictionary<string, object> ObjToDic(object o)
    {
        return o.GetType().GetProperties().ToDictionary(x => x.Name, x => x.GetValue(o));
    }

    static void Main(string[] args)
    {
        var fileNames = Directory.EnumerateFiles("c:\\windows");

        foreach (string name in fileNames)
        {
            Console.WriteLine("==========================================");
            FileInfo fi = new FileInfo(name);
            var propDict = ObjToDic(fi); // <== Here we convert FileInfo to dictionary
            foreach (var item in propDict.AsEnumerable())
            {
                Console.WriteLine(string.Format("{0}: {1}", item.Key, item.Value.ToString()));
            }
        }
    }
}

请记住,在.NET中有属性和字段。在C#中使用相同的语法读取和写入两者,但反射处理它们的方式不同。上面的示例仅显示属性。

答案 1 :(得分:1)

从您的示例中我看到您希望将每个列表项映射到Dictionary。请尝试以下代码:

char data[1000] = "foo";
appendchar(data, 'b');
appendchar(data, 'a');
appendchar(data, 'r');
puts(data);
相关问题