小赖子的英国生活和资讯

简洁的 C# LINQ 写法 – 例子 1

阅读 桌面完整版

LINQ 的全称是Language-Integrated Query, 在 .NET 2.0 之后就可以使用这种简洁的语法. 使用 LINQ 可以使代码变得简短, 清楚.

比如:

1
2
3
4
5
6
7
8
9
10
11
12
public class FileCollection : CollectionBase<string>
{
        public override bool Contains(string item)
        {
            foreach (string str in this)
            {
                if (string.Compare(str, item, true) == 0)
                    return true;
            }
            return false;
        }
}
public class FileCollection : CollectionBase<string>
{
        public override bool Contains(string item)
        {
            foreach (string str in this)
            {
                if (string.Compare(str, item, true) == 0)
                    return true;
            }
            return false;
        }
}

这可以变成 LINQ:

1
2
3
4
5
6
7
public class FileCollection : CollectionBase<string>
{
        public override bool Contains(string item)
        {
            return this.Any(str => string.Compare(str, item, true) == 0);
        }
}
public class FileCollection : CollectionBase<string>
{
        public override bool Contains(string item)
        {
            return this.Any(str => string.Compare(str, item, true) == 0);
        }
}

两种写法并没有什么性能上的区别, 所以LINQ的版本会更好些.

英文: https://helloacm.com/c-example-of-using-linq-1/

强烈推荐

微信公众号: 小赖子的英国生活和资讯 JustYYUK

阅读 桌面完整版
Exit mobile version