请NameValueCollection中接触到LINQ查询 [英] Make NameValueCollection accessible to LINQ Query

查看:570
本文介绍了请NameValueCollection中接触到LINQ查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让的NameValueCollection 访问LINQ查询运算符,如在哪里,加盟,GROUPBY?

How to make NameValueCollection accessible to LINQ query operator such as where, join, groupby?

我试过如下:

private NameValueCollection RequestFields()
{
    NameValueCollection nvc = new NameValueCollection()
                                  {
                                      {"emailOption: blah Blah", "true"},
                                      {"emailOption: blah Blah2", "false"},
                                      {"nothing", "false"},
                                      {"nothinger", "true"}
                                  };
    return nvc;

}

public void GetSelectedEmail()
{
    NameValueCollection nvc = RequestFields();
    IQueryable queryable = nvc.AsQueryable();
}

不过,我得到了一个的的ArgumentException 的告诉我,在源不是IEnumerable的<>

推荐答案

您需要的升降机的非通用的IEnumerable 的IEnumerable&LT ;字符串> 。有人建议你使用 OfType 但这是一个过滤方法。你在做什么是一个演员,因为里面是有演员等效操作符:

You need to "lift" the non-generic IEnumerable to an IEnumerable<string>. It has been suggested that you use OfType but that is a filtering method. What you're doing is the equivalent of a cast, for which there is the Cast operator:

var fields = RequestFields().Cast<string>();

由于弗朗斯指出,这只是提供了访问键。你仍然需要索引到集合中的值。这是一个扩展方法来提取 KeyValuePair <​​/ code>■从的NameValueCollection

public static IEnumerable<KeyValuePair<string, string>> ToPairs(this NameValueCollection collection)
{
    if(collection == null)
    {
        throw new ArgumentNullException("collection");
    }

    return collection.Cast<string>().Select(key => new KeyValuePair<string, string>(key, collection[key]));
}

编辑:为了响应@Ruben Bartelink的要求,这里是如何访问全套每个键使用 ToLookup 值:

In response to @Ruben Bartelink's request, here is how to access the full set of values for each key using ToLookup:

public static ILookup<string, string> ToLookup(this NameValueCollection collection)
{
    if(collection == null)
    {
        throw new ArgumentNullException("collection");
    }

    var pairs =
        from key in collection.Cast<String>()
        from value in collection.GetValues(key)
        select new { key, value };

    return pairs.ToLookup(pair => pair.key, pair => pair.value);
}

这篇关于请NameValueCollection中接触到LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆