是否值得在执行GroupBy()和ToDictionary()之前执行ToList()两次,如下例所示.在创建字典时,ToList()可以最大化性能吗?没有ToList(),Resharper正在大肆宣传可能的多重枚举.
public void SomeMethod(IEnumerable<oldItem> oldItems)
{
var collection = oldItems.Select(i => new item()).ToList();
var dict1 = collection.ToDictionary(i => i.Key);
var dict2 = collection
.GroupBy(i => i.FieldA)
.ToDictionary(g => g.Key, g => new Flags(g.ToArray));
}
Run Code Online (Sandbox Code Playgroud) 不重复:我觉得这不是重复,因为在我的具体情况下,我觉得忽略警告实际上更好.
例如,
IEnumerable<Item> milionItems = GetAMillionItemsFromDatabase();
var item1 = millionItems.FirstOrDefault(x=> x.Condition == "Excellent");
var item2 = millionItems.FirstOrDefault(x=> x.Condition == "Good");
Run Code Online (Sandbox Code Playgroud)
我收到'millionItems'下的警告信息,我知道这意味着什么,但我不确定是否总是值得ToList'去摆脱它.
GetAMillionItemsFromDatabase().ToList();
Run Code Online (Sandbox Code Playgroud)
这看起来很糟糕,因为它会立刻将一百万条记录带入内存.
但是,如果我不这样做并继续枚举IEnumerable,即使它会两次打到数据库,它也不会带来所有数据,因为它会找到第一个匹配项并返回.在这种情况下,在我看来,实际上忽略该消息更好.
以下代码给出了关于IEnumerable可能多次枚举的警告:
public ClassName(IEnumerable<OtherClassName> models) : base(models)
{
_models.AddRange(models);
}
Run Code Online (Sandbox Code Playgroud)
由于"基本"调用,删除此警告的常规解决方案不起作用.我无法转换为列表,因为没有地方存储该列表.
我唯一的选择是让构造函数将列表作为参数吗?在这种情况下,这是推荐的做法吗?
当我对拉取请求进行更改时,我注意到了今天有趣的事情.以下是我的代码:
public List<MatColor> Colors { get; set; }
public List<Customer> Customers { get; set; }
public ProductViewModel()
{
this.Colors = new List<MatColor>();
this.Customers = new List<Customer>();
var products = this.LoadProductViewList();
this.LoadColorComboBox(products);
this.LoadCustomerComboBox(products);
}
public void LoadColorComboBox(IEnumerable<Product> products)
{
this.Colors.Clear();
this.Colors = products.Select(p => new MatColor()
{ Code = p.ColorCode, Description = p.ColorDescription })
.DistinctBy(p => m.Code).DistinctBy(p => p.Description).ToList();
}
private void LoadCustomerComboBox(IEnumerable<Product> products)
{
this.Customers.Clear();
this.Customers = products.Select(p => new Customer()
{ Name = p.CustomerName, Number = p.CustomerNumber })
.DistinctBy(p …Run Code Online (Sandbox Code Playgroud) c# ×4
ienumerable ×3
.net ×1
base ×1
linq ×1
optimization ×1
performance ×1
resharper ×1
wpf ×1