假设我们有一个列表 {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/