![](/img/trans.png)
[英]LINQ: Convert Dictionary<int, Object> to List<List<string>>
[英]LINQ: Convert Dictionary<int, List<MyObject>> to List<List<string>>
我的Dictionary<int, List<MyObject>> result
有..
Key Value
1 {"Chicago", 100}
1 {"Newyork", 200}
2 {"Minneapolis", 300}
想要將其轉換為以下格式的List<List<string>>
。
{"Index", "City","Value"},
{1, "Chicago", 100},
{1, "Newyork", 200}
{2, "Minneapolis", 300}
這是我到目前為止所取得的成就
var list = result.Select(rec => new
{
Index = rec.Key,
City = rec.Value.Select(rec1 => rec1.City),
Value = rec.Value.Select(rec1 => rec1.Value)
}).ToList();
我得到的是這個。
{"Index", "City", "Value"},
{1, System.Linq.Enumerable.WhereSelectListIterator<MyObject, string>, System.Linq.Enumerable.WhereSelectListIterator<MyObject, int>},
{1, System.Linq.Enumerable.WhereSelectListIterator<MyObject, string>, System.Linq.Enumerable.WhereSelectListIterator<MyObject, int>},
{2, System.Linq.Enumerable.WhereSelectListIterator<MyObject, string>, System.Linq.Enumerable.WhereSelectListIterator<MyObject, int>}
可能是我缺少條件。 請提出建議。
public class MyObject
{
public MyObject(){}
public string City{get;set;}
public int Value{get;set;}
}
這是您需要的:
var Result = result.SelectMany(r => r.Value.Select(x => new[] { r.Key.ToString(), x.City, x.Value.ToString() }.ToList()));
要將列名放在外部列表的第一個元素之前:
Result.Insert(0, {"Index", "City","Value"}.ToList());
您是否需要這樣的輸出?
我為您提供解決方案。 試試吧。
Dictionary<int, List<MyObject>> result = new Dictionary<int, List<MyObject>>();
result.Add(1, new List<MyObject>() { new MyObject() { City = "Chicago", Value = 100 }, new MyObject() { City = "Newyork", Value = 200 } });
result.Add(2, new List<MyObject>() { new MyObject() { City = "Minneapolis", Value = 300 } });
var resultYouWant = result.SelectMany(p => p.Value.Select(a => new { Index = p.Key, a.City, a.Value })).ToList();
下面的代碼為您工作,但不能得到您的用例。
var list = result.Select(rec => new
{
Index = rec.Key,
City = rec.Value.City),
Value = rec.Value.Value)
}).ToList();
City = rec.Value.Select(rec1 => rec1.City),
那就是創建一個IEnumerable,而不是一個字符串。 這就是為什么要從中刪除System.Linq.Enumerable.WhereSelectListIterator的原因。
您最好在這里使用for循環。
foreach(var kvp in result)
foreach(var value in kvp)
//Create string here and add it to your list.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.