GroupBy和DistinctBy按属性去重时,内存使用有什么不同?
groupby在遍历过程中会构建完整的分组字典并缓存所有元素,而distinctby仅维护一个已见键的集合并在遇到重复项时直接丢弃后续元素。这意味着在处理大量数据且存在较多重复值时,distinctby的内存占用显著低于groupby,因为它不需要存储被过滤掉的重复对象。

GroupBy如何处理重复元素的内部状态?
GroupBy会为每个唯一的键创建一个列表容器,并将所有匹配该键的元素(包括第一个和后续的重复项)都添加到对应的列表中。这种机制确保了分组后的完整性,但代价是内存中保留了所有原始数据的副本。

using System;
using System.Collections.Generic;
using System.Linq;
public class Item {
public string Category { get; set; }
public int Value { get; set; }
}
public class Program {
public static void Main() {
var items = new List<item> {
new Item { Category = "A", Value = 1 },
new Item { Category = "A", Value = 2 },
new Item { Category = "B", Value = 3 },
new Item { Category = "A", Value = 4 }
};
var groups = items.GroupBy(x => x.Category);
foreach (var group in groups) {
Console.WriteLine($"Key: {group.Key}, Count: {group.Count()}");
}
}
}</item>
DistinctBy在遇到重复键时的行为是什么?
DistinctBy基于“首次出现”原则工作,它只保留具有唯一键的第一个元素,后续具有相同键的元素会被立即忽略且不进入结果序列。这种流式处理方式使得内存中只需保存键的哈希集合,无需存储被丢弃的对象引用。

using System;
using System.Collections.Generic;
using System.Linq;
public class Item {
public string Category { get; set; }
public int Value { get; set; }
}
public class Program {
public static void Main() {
var items = new List<item> {
new Item { Category = "A", Value = 1 },
new Item { Category = "A", Value = 2 },
new Item { Category = "B", Value = 3 },
new Item { Category = "A", Value = 4 }
};
var distinctItems = items.DistinctBy(x => x.Category);
foreach (var item in distinctItems) {
Console.WriteLine($"Category: {item.Category}, Value: {item.Value}");
}
}
}</item>










