2017-08-02 89 views
-5

遇到問題嘗試在dictionary <int, IList<string>>的數據投影到具有的C#:字典的投影<INT,IList的<string>>使用LINQ

public class MyClass { 
    public int Id {get; set;} 
    public string Info {get; set;} 
} 

private Dictionary<int, IList<string>> myData; 

結構現在myData的一類類的平面列表是一個包含信息列表的Id。我需要得到它變成一個列表

,使得MyClass的名單將有這樣的值:

Id = 1, Info = "line 1" 
Id = 1, Info = "line 2" 
Id = 1, Info = "line 3" 
Id = 2, Info = "something else" 
Id = 2, Info = "another thing" 

沒有得到接近突出這一點。圖使用SelectMany,但沒有得到任何東西來匹配這個。

+0

讓我知道如何改進這一點。 ..覺得很清楚。不需要否定這個問題。 – user1161137

+2

'myData.SelectMany(kvp => kvp.Value.Select(v => new MyClass {Id = kvp.Key,Info = v}));' – juharr

+1

您的問題非常廣泛,缺乏任何證據證明您做出了任何努力要嘗試任何事情,不要介意一個好的[mcve]清楚地表明你有什麼特別的問題。它太模糊了,我最初誤解了你甚至想要做的事情。 –

回答

1

你可以做這樣的事情,使用System.Linq

List<MyClass> classList = myData.Keys 
    .SelectMany(key => myData[key], (key, s) => new MyClass {Id = key, Info = s}) 
    .ToList(); 

例如:

static void Main(string[] args) 
{ 
    // Start with a dictionary of Ids and a List<string> of Infos 
    var myData = new Dictionary<int, List<string>> 
    { 
     {1, new List<string> {"line 1", "line 2", "line 3" } }, 
     {2, new List<string> {"something else", "another thing" } }, 
    }; 

    // Convert it into a list of MyClass objects 
    var itemList = myData.Keys 
     .SelectMany(key => myData[key], (key, s) => new MyClass { Id = key, Info = s }) 
     .ToList(); 

    // Output each MyClass object to the Console window 
    Console.WriteLine("The list of MyClass contains the following objects:"); 
    foreach(var item in itemList) 
    { 
     Console.WriteLine($"MyClass: Id = {item.Id}, Info = {item.Info}"); 
    } 

    Console.Write("\nDone!\nPress any key to exit..."); 
    Console.ReadKey(); 
} 

輸出

enter image description here

+0

非常感謝Rufus。這是我正在尋找...雖然我喜歡juharr解決方案好一點..更容易編寫imo ... myData.SelectMany(kvp => kvp.Value.Select(v => new MyClass {Id = kvp。 Key,Info = v}));但是我會把你的答案標記爲答案,因爲他沒有「回答」這個問題,你的解決方案也很好! – user1161137

1

這是你在找什麼?

List<MyClass> Project(Dictionary<int, IList<string>> data) 
{ 
    List<MyClass> result = new List<MyClass>(); 
    foreach (int key in data.Keys) 
     foreach (string s in data[key]) 
      result.Add(new MyClass { Id = key, Info = s }); 
    return result; 
} 

這個想法是遍歷每個int,並在其中迭代每個與該int相關聯的字符串。並將所有這些組合(int和string)添加到結果中。

相關問題