2009-06-26 76 views

回答

8

我不確定,如果你想在新的KeyValuePair值是該類型或單個元素的枚舉。這裏有兩個版本

IEnumerable的版本

var toReturn = source.Select(x => new KeyValuePair<SomeType,IEnumerable<SomeOtherType>>(x.Key, x.Value.Take(1)); 

不可枚舉的版本

var toReturn = source.Select(x => new KeyValuePair<SomeType,SomeOtherType>(x.Key,x.Value.First()); 
+1

感謝一大堆,我需要的第一個版本。我實際上嘗試過,但忘了在KeyValuePair中指定類型,並且出現錯誤。 – epitka 2009-06-26 14:43:15

6

所有你缺少的是KeyValuePair的使用類型。你可以使用Jared的lambda表達式的版本,或者如果你喜歡的查詢表達式語法:

var toReturn = from kv in source 
       select new KeyValuePair<MyType, OtherType>(kv.Key, 
                  kv.Value.First()); 

如果你不想顯式地指定類型參數,你可以創建你自己的助手和使用類型推斷:

// Non-generic helper class. 
public static class KeyValuePair 
{ 
    public static KeyValuePair<TKey, TValue> Of(TKey key, TValue value) 
    { 
     return new KeyValuePair<TKey, TValue>(key, value); 
    } 
} 

此時您的查詢就會變成:

var toReturn = from kv in source 
       select KeyValuePair.Of(kv.Key, kv.Value.First()); 

var toReturn = source.Select(kv => KeyValuePair.Of(kv.Key, kv.Value.First()); 

編輯:哎呀 - 我想我也會誤讀你的問題。如果你希望它是完全相同的類型,即取值爲枚舉過的,只是使用Take(1)代替First()

var toReturn = source.Select(kv => KeyValuePair.Of(kv.Key, kv.Value.Take(1)); 

(是不是類型推斷可愛:)

+0

我調用了我的「Of」方法「Create」,但我真的很喜歡這種方法,當我需要手動創建KeyValuePairs時... – 2009-06-26 17:24:04

0

爲什麼呢?你想獲得相同類型的集合?當你只有第一個元素時,你不需要一個集合(IEnumerable<OtherType>),而只需要一個值(OtherType)。

這(就像你貼的那個)應該是正確的(你只需要添加泛型參數爲KeyValuePair)

var toReturn = from kv in source select new KeyValuePair<SomeType, OtherType>(kv.Key, kv.Value.First()); 

如果你真的想要得到的相同類型的集合,寫

var toReturn = from kv in source select new KeyValuePair<SomeType, IEnumerable<OtherType>>(kv.Key, new [] { kv.Value.First() }); 

注意:當將此函數包裝到泛型函數中時,不需要爲KeyValuePair提供顯式類型參數。

KeyValuePair<TKey, TValue> Pair<TKey, TValue>(TKey key, TValue value) { 
    return new KeyValuePair<TKey, TValue>(key, value); 
} 
// 
var foo = Pair(1, "Hello"); 
+0

我需要一個相同的類型,以便能夠將其管道到處理其他方法一。這是按日期創建desc命令,我需要顯示所有或最新的。 – epitka 2009-06-26 14:48:33

1
var toReturn = source 
.ToDictionary(
    kvp => kvp.Key, 
    kvp => kvp.Value.Take(1) 
); 
相關問題