How to make NameValueCollection
accessible to LINQ query operator such as where, join, groupby?
I tried the below:
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();
}
But I got an ArgumentException telling me that the source is not IEnumerable<>.
I know I'm late to the party but just wanted to add my answer that doesn't involve the
.Cast
extension method but instead uses the AllKeys property:This would allow the following extension method:
Hope this helps any future visitors
I don't really see why anyone would need to add an extension method.
Here's some different ways to do it in VB.NET. It includes 4 different intermediate forms of IEnumerable: Array, Tuple, Anonymous, and KeyValuePair. For the C# equivalent go to converter.telerik dot com and convert it.
The problem is that the collection implements
IEnumerable
(as opposed toIEnumerable<T>
) and enumerating the collection returns the keys, not the pairs.If I were you, I'd use a
Dictionary<string, string>
which is enumerable and can be used with LINQ.AsQueryable
must take anIEnumerable<T>
, a generic.NameValueCollection
implementsIEnumerable
, which is different.Instead of this:
Try OfType (it accepts the non-generic interface)
For me, @Bryan Watts' (+1'd) answer's
ToLookup
variant represents by far the clearest approach for using it on a read-only basis.For my use case, I'm manipulating a query string for use with Linq2Rest and also need to turn it all back into a
NameValueCollection
at the end, so I have a set of extension methods forNameValueCollection
which offer more granular operations (to operate both per parameter name (AsEnumerable
) and per argument (AsKeyValuePairs
)) and also the inverse operation of converting it backToNameValueCollection
(from either representation)).Example consumption:
Code:
A dictionary is probably actually closer to what you want to use since it will actually fill more of the roles that NameValueCollection fills. This is a variation of Bryan Watts' solution: