2011-04-15 125 views
0

考慮到這種結構......複雜的LINQ查詢

List<IEnumerable<KeyValuePair<String, String>>> 

你會怎麼寫了下面的僞代碼LINQ查詢...

SELECT 
    /* Count of how many [KeyValuePair] exists in [List] */ 
FROM 
    [List] 
WHERE 
     [KeyValuePair].Key == "foo" 
    AND Int32.Parse([KeyValuePair].Value.Replace(".", "")) > 10 

...?


更新

上面的查詢,aginst下面的列表中運行的結果,應該是6(SIX)...

var list = new List<IEnumerable<KeyValuePair<String, String>>> 
{ 
    new [] 
    { 
     new KeyValuePair<String, String>("foo", "1.1"), 
     new KeyValuePair<String, String>("foo", "1.2"), 
     new KeyValuePair<String, String>("foo", "1.3") 
    },            

    new []           
    {            
     new KeyValuePair<String, String>("foo", "0.1"), 
     new KeyValuePair<String, String>("foo", "0.2"), 
     new KeyValuePair<String, String>("foo", "0.3") 
    },            

    new []           
    {            
     new KeyValuePair<String, String>("foo", "2.1"), 
     new KeyValuePair<String, String>("foo", "2.2"), 
     new KeyValuePair<String, String>("foo", "2.3") 
    } 
}; 
+0

你能提供的原始列表中的內容的例子嗎? – 2011-04-15 10:28:47

+0

你最初的查詢不太合理,大於10的是什麼,因爲它看起來像你在那裏比較一個字符串? – 2011-04-15 10:52:52

+0

更新了我的代碼 – roosteronacid 2011-04-15 11:01:37

回答

0

我得到6從這...

var result = list.Sum(item=>item.Count(kp=>kp.Key == "foo" && int.Parse(kp.Value.Replace(".",String.Empty))>10)); 
0
var result = list.SelectMany(ary =>aryx).Count(item => item.Key == "Foo" && Int32.Parse(item.Value.Replace(".", "")) > 10); 

雖然我猜你正在取代「。」因爲你想擺脫成千上萬的分隔符,所以你可能想要: Int32.Parse(item.Value, NumberStyles.AllowThousands, CultureInfo.CurrentCulture)確保你已經適當地設置了當前文化。

我可能會寫它的清晰度是這樣的:

var result = list.SelectMany(ary => ary) 
       .Where(item => item.Key.Equals("Foo", StringComparison.CurrentCulture)) 
       .Select(item => 
         Int32.Parse(item.Value.Replace(".", "")) 
       .Count(value=> value> 10); 

理解語法可能看起來像:

var q = from @array in list 
     from kvp in array 
     where kvp.Key.Equals("Foo", StringComparison.CurrentCulture) 
     select .Parse(item.Value.Replace(".", "")); 
var result = q.Count(value => value > 10); 
+0

什麼是item.childitem?項目是IEnumerable本身... – 2011-04-15 11:00:44

+0

我不知道。回來了,一切都改變了。將我的代碼更新到最新的問題。 – Talljoe 2011-04-15 11:04:33

+0

哈哈 - 當它發生時就討厭它 – 2011-04-15 11:04:54