如何使LINQ查询操作符,如where,join,groupby访问NameValueCollection
?
我尝试了以下几种方法:
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<>。
发布于 2008-12-28 18:38:04
您需要将非泛型IEnumerable
“提升”为IEnumerable<string>
。有人建议您使用OfType
,但这是一种过滤方法。您所做的等同于强制转换,其中包含Cast
运算符:
var fields = RequestFields().Cast<string>();
正如Frans所指出的,这只提供了对密钥的访问。您仍然需要为这些值索引到集合中。下面是一个从NameValueCollection
中提取KeyValuePair
的扩展方法
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
访问每个键的全套值
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);
}
或者,使用C# 7.0元组:
public static IEnumerable<(String name, String value)> ToTuples(this NameValueCollection collection)
{
if(collection == null)
{
throw new ArgumentNullException("collection");
}
return
from key in collection.Cast<string>()
from value in collection.GetValues(key)
select (key, value);
}
发布于 2008-12-24 15:15:23
AsQueryable
必须接受泛型类型的IEnumerable<T>
。NameValueCollection
实现了IEnumerable
,这是不同的。
而不是这样:
{
NameValueCollection nvc = RequestFields();
IQueryable queryable = nvc.AsQueryable();
}
试试OfType (它接受非泛型接口)
{
NameValueCollection nvc = RequestFields();
IEnumerable<string> canBeQueried = nvc.OfType<string>();
IEnumerable<string> query =
canBeQueried.Where(s => s.StartsWith("abc"));
}
发布于 2013-09-17 23:59:43
我知道我来晚了,但我只是想补充一下我的答案,它不涉及.Cast
扩展方法,而是使用AllKeys属性:
var fields = RequestFields().AllKeys;
这将允许使用以下扩展方法:
public static IEnumerable<KeyValuePair<string, string>> ToPairs(this NameValueCollection collection)
{
if(collection == null)
{
throw new ArgumentNullException("collection");
}
return collection.AllKeys.Select(key => new KeyValuePair<string, string>(key, collection[key]));
}
希望这对任何未来的访问者有所帮助
https://stackoverflow.com/questions/391023
复制相似问题