如何通过Key属性匹配lookup列表更新list的ValueToGet属性?
如何通过Key属性匹配listLookup来更新list的ValueToGet属性
最高效的方式是先将listLookup转换为字典,利用字典的O(1)查找特性提升性能,尤其在数据量较大时优势明显:
实现步骤:
- 将
listLookup转换为以KeyLookup为键、ValueLookup为值的字典 - 遍历
list中的每个WidgetA实例,通过字典快速匹配对应值并赋值给ValueToGet
完整代码示例:
using System.Collections.Generic; using System.Linq; // 需要引入Linq命名空间来使用ToDictionary方法 public class Program { public static void Main() { //Arrange var key1 = new WidgetA{Id = 1, Key = 50}; var key2 = new WidgetA{Id = 1, Key = 100}; var key3 = new WidgetA{Id = 1, Key = 150}; List<WidgetA> list = new List<WidgetA>(); list.Add(key1); list.Add(key2); list.Add(key3); var keyLookup1 = new WidgetB() {Id = 1, KeyLookup = 50, ValueLookup = "Fifty"}; var keyLookup2 = new WidgetB() {Id = 2, KeyLookup = 100, ValueLookup = "One hundred"}; var keyLookup3 = new WidgetB() {Id = 3, KeyLookup = 150, ValueLookup = "One hundred and fifty"}; List<WidgetB> listLookup = new List<WidgetB>(); listLookup.Add(keyLookup1); listLookup.Add(keyLookup2); listLookup.Add(keyLookup3); //Act // 转换为字典,优化查找效率 var lookupDictionary = listLookup.ToDictionary(widget => widget.KeyLookup, widget => widget.ValueLookup); foreach (var widget in list) { // 尝试从字典中获取匹配值,避免KeyNotFoundException if (lookupDictionary.TryGetValue(widget.Key, out var matchedValue)) { widget.ValueToGet = matchedValue; } // 可选:处理无匹配项的情况 // else { widget.ValueToGet = "未找到匹配值"; } } // 验证结果(可选) foreach (var item in list) { System.Console.WriteLine($"Key: {item.Key}, ValueToGet: {item.ValueToGet}"); } } } public class WidgetA { public int Id { get; set; } public int Key { get; set; } public string ValueToGet { get; set; } } public class WidgetB { public int Id { get; set; } public int KeyLookup { get; set; } public string ValueLookup { get; set; } }
备选方案(小数据量场景)
如果数据量很小,也可以直接遍历匹配,无需转换字典,但性能会随数据量增长而下降:
foreach (var widget in list) { var matchedWidget = listLookup.FirstOrDefault(b => b.KeyLookup == widget.Key); if (matchedWidget != null) { widget.ValueToGet = matchedWidget.ValueLookup; } }
注意事项
- 使用
ToDictionary时,确保KeyLookup值唯一,否则会抛出ArgumentException;如果存在重复键,可以改用ToLookup处理。 - 用
TryGetValue替代直接索引字典,避免因无匹配键抛出KeyNotFoundException。
内容的提问来源于stack exchange,提问作者Rod
相关产品推荐
相关产品推荐

