将LINQ与实现非通用ICollection的类一起使用 [英] Using LINQ with classes implementing non-generic ICollection

查看:156
本文介绍了将LINQ与实现非通用ICollection的类一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对MatchCollection对象运行LINQ查询,但是发现这是不可能的,因为它没有实现ICollection<T>,仅实现了ICollection.

I wanted to run a LINQ query against a MatchCollection object but found this wasn't possible as it doesn't implement ICollection<T>, just ICollection.

就代码简洁性,性能和内存使用而言,将LINQ与非通用集合一起使用的最佳选择是什么?

What is the best option for using LINQ with non-generic collections, both in terms of code conciseness but also performance and memory usage?

(如果感兴趣,这是非LINQuified代码:)

(If interested, here is the non-LINQuified code:)

MatchCollection fieldValues = Regex.Matches(fieldValue, @"(?<id>\d+);#(?<text>[^;|^$]+)");
foreach (Match m in fieldValues)
{
    if (m.Groups["text"].Value.Equals(someString))
    {
        // Do stuff
    }
}

推荐答案

您也可以在LINQ中包含someString过滤器.

You can include your someString filter with LINQ as well.

var matches = Regex.Matches(fieldValue, @"(?<id>\d+);#(?<text>[^;|^$]+)");
var textMatches = from Match m in matches
                  where m.Groups["text"].Value.Equals(someString)
                  select m;

foreach (Match m in textMatches)
{
    // Do stuff
}

请注意,编译器会翻译这样的查询...

Note that the compiler translates a query like this...

var q = from MyType x in myEnum select x;

...进入这个...

...into this...

var q = from x in myEnum.Cast<MyType>() select x;

...因此同时包含类型和Cast<T>()是多余的.

...so including both the type and Cast<T>() is redundant.

在性能方面,Cast<T>()只是执行显式类型转换并产生值,因此对性能的影响可以忽略不计.对于不确定所有成员是否都属于所需类型的旧式收藏,可以使用OfType<T>()代替.

Performance-wise, Cast<T>() just does an explicit type cast and yields the value, so the performance hit will be negligible. For legacy collections where you're not sure all members are of the desired type, you can use OfType<T>() instead.

这篇关于将LINQ与实现非通用ICollection的类一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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