慕哥9229398
结论我对下面的所有方法以及un-lucky的答案进行了一些测试,其中最快的是下面的选项2,即var results = theObjects.Join(idList, o => o.id, id => id, (o, id) => o).ToList();results.ForEach(o => o.selected = true);使用 Linq 执行此操作的另一种方法,我们在其中迭代theObjects并检查每个以查看其 id 是否存在于idList:1var result = theObjects.ForEach(o => o.selected = idList.Contains(o.id) ? true : false);或使用Joinand ForEach,我们首先使用提取匹配的项目Join,然后遍历这些项目:2var results = theObjects.Join(idList, o => o.id, id => id, (o, id) => o).ToList();results.ForEach(o => o.selected = true);或者,您可以Select与ForEach和一起使用FirstOrDefault。这可能会比其他两个慢:3theObjects .Select(o => o.id) .Where(i => idList.Contains(i)).ToList() .ForEach(i => theObjects.FirstOrDefault(o => o.id == i).selected = true);我对我发布的 3 种方法进行了一些测试,其中我们有 10000MyObject秒和 1000 个唯一 ID。我运行每种方法 1000 次,然后得到每个方法的平均值ElapsedMillliseconds。结果是18.288 毫秒20.19 毫秒357.342 毫秒one = 0;two = 0;three = 0;for (var i = 0; i <1000; i++) { RunTest();}oneMean = one / 1000;twoMean = two / 1000;threeMean = three / 1000;在哪里private void RunTest(){ ResetData(); var stopwatch = Stopwatch.StartNew(); theObjects.ForEach(o => o.selected = idList.Contains(o.id) ? true : false); stopwatch.Stop(); one += stopwatch.ElapsedMilliseconds; ResetData(); stopwatch = Stopwatch.StartNew(); var results = theObjects.Join(idList, o => o.id, id => id, (o, id) => o).ToList(); results.ForEach(o => o.selected = true); stopwatch.Stop(); two += stopwatch.ElapsedMilliseconds; ResetData(); stopwatch = Stopwatch.StartNew(); theObjects .Select(o => o.id) .Where(i => idList.Contains(i)).ToList() .ForEach(i => theObjects.FirstOrDefault(o => o.id == i).selected = true); stopwatch.Stop(); three += stopwatch.ElapsedMilliseconds;}private void ResetData(){ theObjects = new List<MyObject>(); idList = new List<int>(); var rnd = new Random(); for (var i=0; i<10000; i++) { theObjects.Add(new MyObject(){id = i}); } for (var i=0; i<=1000; i++) { var r = rnd.Next(0, 1000); while (idList.Contains(r)) { r = rnd.Next(0, 10000); } idList.Add(r); }}我测试了un-lucky的答案(现在最多投票),平均得分为 147.676foreach(var obj in theObjects.Where(o => idList.Any(i=> i == o.id))){ obj.selected = true;}