复杂的LINQ查询

时间:2011-04-15 10:25:06

标签: 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

...


更新

上面的查询结果,运行在下面的列表中,应该是6(六)...

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")
    }
};

2 个答案:

答案 0 :(得分:0)

我从这里得到6 ......

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

答案 1 :(得分: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);