开发者

Complex LINQ query

开发者 https://www.devze.com 2023-02-25 05:46 出处:网络
Considering this structure... List<IEnumerable<KeyValuePair<String, String>>> How would you write a LINQ query for the following pseudo-code...

Considering this structure...

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

How would you write a LINQ query for the following pseudo-code...

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

...?

Update

The result of the above query, run aginst the list below, should be 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 Key开发者_Python百科ValuePair<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")
    }
};


I get 6 from this...

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


var result = list.SelectMany(ary =>aryx).Count(item => item.Key == "Foo" && Int32.Parse(item.Value.Replace(".", "")) > 10);

Although I'm guessing you're replacing the "." because you want to get rid of thousands separators, so You might want: Int32.Parse(item.Value, NumberStyles.AllowThousands, CultureInfo.CurrentCulture) making sure you have the Current Culture set appropriately.

I might write it for clarity like this:

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

Comprehension syntax might look like:

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

精彩评论

暂无评论...
验证码 换一张
取 消