我有一个List<string>
的字典,每个元素看起来像这样:
(key): '23895'
(List<string>): ['00185801']
我想将其转换为具有这些字符串作为属性的对象:
title: '23895'
orderNumber: '00185801'
我现在做的方式是,我有一个课程OrderNumber
:
namespace myApp
{
class OrderNumber
{
public string title;
public string orderNumber;
public OrderNumber(string title, string orderNumber)
{
this.title = title;
this.orderNumber = orderNumber;
}
}
}
并且我将List<string>
的字典转换为List<OrderNumber>
如下:
private void convertDictListsToObjects(Dictionary<string,List<string>> orderNumberDict)
{
orderNumberObjList = new List<OrderNumber>();
foreach(string key in orderNumberDict.Keys){
List<string> orderNumberList=orderNumberDict[key];
OrderNumber orderNumberObj = new OrderNumber(key, orderNumberList[0]);
orderNumberObjList.Add(orderNumberObj);
}
}
我有几种不同类型的Dictionary<string,List<string>>
,List<string>
中元素的数量不同,我的目标是在它们上使用Enumerable.Join()
,但是我需要将它们转换为具有属性名称的对象列表,例如上面的OrderNumber
类以执行.Join()
。是否有比我已经使用过的方法更简单的方法,或者是否需要使用这种技术,为每种List<string>
类型制作一个单独的类?
将convertDictListsToObjects
的实现更改为此:
A Dictionary<K, V>
实现IEnumerable<KeyValuePair<K, V>>
。使用System.Linq.Select
将字典的每个KeyValuePair<string, List<string>>
转换为OrderNumber实例。