2010-03-16 48 views
0

我已經發布過此文,但我的文章很差。我正在嘗試一個更深思熟慮的結構。用於複雜數據合併的LINQ查詢代碼

我有下面的代碼,我試圖找出更短的linq表達式來做'內聯'。請檢查底部附近的「Run()」方法。我試圖理解如何基於一個對象中的匹配標識符將兩個字典連接在一起,以便我可以在這種語法中使用查詢。

var selected = from a in items.List() 
       // etc. etc. 
       select a; 

,這樣我可以定義我的代碼狀結構...

TModelViewModel = new TModelViewModel 
{ 
TDictionary = from a in items... etc. etc... 
} 

,而不是通過一串foreach循環,額外的對象申報的打算,等


這是我的班級結構。 Run()方法就是我試圖簡化的方法。我基本上需要在幾個地方進行內聯轉換,並且我想簡化它,使我可以更「乾淨地」定義它。

class TModel 
{ 
    public Guid Id { get; set; } 
} 
class TModels : List<TModel> 
{ 
} 
class TValue 
{ 
} 

class TStorage 
{ 
    public Dictionary<Guid, TValue> Items { get; set; } 
} 

class TArranged 
{ 
    public Dictionary<TModel, TValue> Items { get; set; } 
} 
static class Repository 
{ 
    static public TItem Single<TItem, TCollection>(Predicate<TItem> expression) 
    { 
     return default(TItem); // access logic. 
    } 
} 

class Sample 
{ 
    public void Run() 
    { 
     TStorage tStorage = new TStorage(); 
     // access tStorage logic here. 

     Dictionary<TModel, TValue> d = new Dictionary<TModel, TValue>(); 

     foreach (KeyValuePair<Guid, TValue> kv in tStorage.Items) 
     { 
      d.Add(Repository.Single<TModel, TModels>(m => m.Id == kv.Key),kv.Value); 
     } 
    } 
} 

回答

1

還沒有真正進行了測試,這是相當難看,但我覺得應該工作:

 Dictionary<TModel, TValue> d = new Dictionary<TModel, TValue>(); 

     d = d.Concat(tStorage 
      .Items 
      .Select(i => new KeyValuePair<TModel, TValue>(
       new TModel { Id = i.Key }, i.Value))).ToDictionary(i => i.Key, i => i.Value); 
+0

Hrnm。儘管如此,我沒有看到它訪問TModel項目的任何地方。 – Ciel 2010-03-16 15:56:51

+0

啊哈,找到它了。在第三行,其中Id = i.Key。我會將其設置爲識別存儲庫中的匹配的謂詞表達式。此代碼完美工作,非常感謝!我能打擾你解釋一​​下發生了什麼?我不確定它爲什麼有效。 – Ciel 2010-03-16 16:06:55