‘将’Dictionary 转换为List
我有一个Dictionary dictionary1
,我需要将它转换为List
,其中Data
具有属性lable
= dictionary1.key和value
= dictionary1.value。 我不想使用for / foreach循环(由我自己编写),因为为了避免它我试图使用Dictionary。
另一种选择是拥有两个不同的词典(dictionary2和dictionary3),其中dictionary2
和dictionary3
。
我有道理吗? 那可能吗? 有更好的选择吗?
假设:
class Data { public string Label { get; set; } public int Value { get; set; } }
然后:
Dictionary dic; List list = dic.Select(p => new Data { Label = p.Key, Value = p.Value }).ToList();
也许你可以使用LINQ?
dictionary1.Select(p => new Data(p.Key, p.Value)).ToList()
然而,这是使用yield
,因此在后台循环…
myDictionary.Select(x => new Data(){ label = x.Key, value = x.Value).ToList();
我假设“无循环”实际上意味着“我想要LINQ”:
List = dictionary1.Select( pair => new Data() { label = pair.Key, value = pair.Value })).ToList();
尝试
dictionary1.Select(p => new Data(p.Key, p.Value)).ToList();
.NET已经有一种数据类型可以执行Data
操作: KeyValuePair
。 Dictionary已经实现了IEnumerable
,只是强制转换为它。
Dictionary blah = new Dictionary(); IEnumerable> foo = blah;
这是一个老post,但post只是为了帮助其他人;)
转换任何对象类型的示例:
public List Select (string filterParam) { DataTable dataTable = new DataTable() //{... implement filter to fill dataTable } List> rows = new List>(); Dictionary row; foreach (DataRow dr in dataTable.Rows) { row = new Dictionary(); foreach (DataColumn col in dataTable.Columns) { row.Add(col.ColumnName, dr[col]); } rows.Add(row); } string json = new JavaScriptSerializer().Serialize(rows); using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json))) { DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T[])); var tick = (T[])deserializer.ReadObject(stream); return tick.ToList(); } }
public class Data { public string Key { get; set; } public int Value { get; set; } } private static void Main(string[] args) { Dictionary dictionary1 = new Dictionary(); dictionary1.Add("key1", 1); dictionary1.Add("key2", 2); List data = dictionary1.Select(z => new Data { Key = z.Key, Value = z.Value }).ToList(); Console.ReadLine(); }
以防万一只是帮助任何人,我这样做 – 将处理比单个值类型更复杂的对象,如OP所述。
// Assumes: Dictionary MyDictionary; List list = new List (); list.AddRange(MyDictionary.Values.ToArray());