c# - LINQ 过滤对象列表

标签 c# asp.net .net linq

我在内存中有一个列表。它包含我数据库中的所有产品。这保存在缓存中。

根据 QueryString,我需要过滤该产品列表并将转发器绑定(bind)到它。

因此,我将 LINQ .Where 子句应用于我的列表,但如您所知,Where 返回 IEnumerable

如果我有

var category = "Beverages";
var filteredProducts = allProducts.Where(p => p.Category = category);

当我调用 filteredProducts.ToList() 时会发生什么?

请注意,allProducts 是一个 List() 并且包含大约 300 个项目。

我猜它会在内存中创建一个新的 List 并从 allProducts 列表中复制相关项目。

filteredProducts 大约是。 60 项。

这在性能方面有多糟糕?

编辑:它是一个网络应用程序,所以我们正在谈论假设同时向该页面发出数十个请求,这可能会影响性能。

最佳答案

感觉就像为了演示目的而编写一些愚蠢的代码。此演示的目的是让您看到在 IEnumerable< 上调用 .ToList() 时,只有对象的 引用 被复制到新创建的列表中。因此,基础对象在您的原始列表和新列表中都是相同的。这有两个含义。首先,没有低效的对象深拷贝。其次,对原始列表中的项目和新列表中的项目所做的更改将影响两个列表,因为对象在内存中相同。将其放入控制台应用程序以查看输出。

class Program
{
    class Dog
    {            
        public string name { get; set; }
        public bool isAGoodBoy { get; set;}
        public Dog(string name, bool isAGoodBoy)
        {
            this.name = name;
            this.isAGoodBoy = isAGoodBoy;
        }
    }

    static void Main(string[] args)
    {            
        List<Dog> doges = new List<Dog>();
        doges.Add(new Dog("Rufus", true));
        doges.Add(new Dog("Kevin", false)); //chewed furniture
        doges.Add(new Dog("Maximus", true));

        IEnumerable<Dog> goodBoys = doges.Where(doggy => doggy.isAGoodBoy);
        List<Dog> goodBoysList = goodBoys.ToList();
        foreach (var goodBoy in goodBoysList)   //Iterate over NEW list
        {
            goodBoy.isAGoodBoy = false;    //They wouldn't stop barking
        }

        //From original list! You'll see all of these will output 'False'
        Console.WriteLine("Is Rufus good? " + doges[0].isAGoodBoy.ToString());    
        Console.WriteLine("Is Kevin good? " + doges[1].isAGoodBoy.ToString());    
        Console.WriteLine("Is Maximus good? " + doges[2].isAGoodBoy.ToString());    

        Console.ReadLine();

    }
}

关于c# - LINQ 过滤对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26901081/

相关文章:

c# - 来自 C# 的 Active Directory 查找在服务器上失败但在本地工作

c# - 如何清除 javascript 中 OnUnload 事件中的 asp.net session 值

c# - 写长的if语句更简洁

c# - 当您声明一个没有实例的对象时,.Net 会做什么?

c# - 在父类(super class)的代码中找不到控件

.Net 单选按钮类

c# - .NET核心JWE : no "cty" header

c# - 在 WPF 中使用数据绑定(bind)时 OxyPlot 不刷新

c# - .NET 和 C# 异常。抓什么才合理

c# - 带 Linq 的 BLToolkit——为什么需要 `using` 语句?