整个if prevValue!= currValue循环中的东西

cle*_*ine 2 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
}
Run Code Online (Sandbox Code Playgroud)

有没有替代方案?它看起来很狡猾.

编辑:使代码对于手头的问题更加真实.

Mar*_*ell 5

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

foreach(string s in theList.Distinct()) {
   doSomething(); // with s
}
Run Code Online (Sandbox Code Playgroud)

重新更新; 也许使用类似的东西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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)