c# - 整个 If prevValue != currValue 循环中的事情

标签 c# loops list

假设我们有一个列表 {a, a, a, b, b, c, c }

我们想遍历列表并在项目值更改时进行某种更改...例如:

prevEmployer = String.empty;
foreach(Person p in PersonList){
  if(p.Employer != prevEmployer){ 
    doSomething(); 
    prevEmployer = p.Employer;
  }
  ... more code
}

除此之外还有其他选择吗?它对我来说看起来很笨拙。

编辑:使代码更符合手头的问题。

最佳答案

您想要不同的值吗?即会有 {a,a,a,b,b,a,c,c,a} 吗?如果没有,您可以使用 LINQ:

foreach(string s in theList.Distinct()) {
   doSomething(); // with s
}

回复您的更新;也许使用像 DistinctBy 这样的东西:

foreach(var item in data.DistinctBy(x=>x.Foo)) {
    Console.WriteLine(item.Bar);
}

public static IEnumerable<TSource> DistinctBy<TSource,TValue>(
        this IEnumerable<TSource> source, Func<TSource,TValue> selector) {
    var set = new HashSet<TValue>();
    foreach (var item in source) {
        if (set.Add(selector(item))) {
            yield return item;
        }
    }
}

关于c# - 整个 If prevValue != currValue 循环中的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/667804/

相关文章:

java - 需要一种不断循环/迭代 map 的方法

c# - 尝试使用 WPF 创建一个 ListBox,我想通过代码填充成员

list - Dart :检查列表列表中的项目

c# - 这个请求是由 EF Core buggy 生成的还是我的代码?

c# - 注销代码不适用于 Jquery 验证

r - 使用新数据集在 purrr::map 之后预测 glm 模型的概率

jquery - 循环创建多个 div 元素?查询器

python - 对多个输入集的理解

c# - EPPlus 不下载带有模板的 Excel 文件

C# - 管道样式事件模型