【发布时间】:2011-10-16 12:18:44
【问题描述】:
如何存储大型集合的多个值,以便能够使用基于具有非唯一值的属性的 lambda 表达式快速找到它们?
示例案例(未针对性能进行优化):
class Product
{
public string Title { get; set; }
public int Price { get; set; }
public string Description { get; set; }
}
IList<Product> products = this.LoadProducts();
var q1 = products.Where(c => c.Title == "Hello"); // 1 product.
var q2 = products.Where(c => c.Title == "Sample"); // 5 products.
var q3 = products.Where(c => string.IsNullOrEmpty(c.Title)); // 12 345 products.
如果标题是唯一的,则使用IDictionary 或HashSet 可以轻松优化性能。但是值不唯一的情况呢?
【问题讨论】:
-
可能是在
Title上排序的二叉搜索树(如果这是您需要找到的唯一属性) -
您的最后一个查询无法编译。你的意思是
string.IsNullOrEmpty(c.Title)?
标签: c# linq optimization query-optimization