c# - 是否可以在迭代 ICollection 时确定当前位置?

标签 c# .net .net-2.0 foreach icollection

我有以下代码:

foreach(string reelid in unValidatedFeedersOnMachine.Keys)
{
    _sqlString.Append("CompID = '").Append(reelid).Append("' ");
}

我需要在每次迭代 .Appened("or ") 中添加该循环,但最后一次除外。

知道如何知道我何时位于此处的最后一次迭代吗?

最佳答案

我会反其道而行之 - 将第一个视为异常更简单:

bool first = true;
foreach(string reelid in unValidatedFeedersOnMachine.Keys)
{
   if(first) {first = false;}
   else {_sqlString.Append(" or ";}
    _sqlString.Append("CompID = '").Append(reelid).Append("' ");
}

或者在 .NET 4.0 中使用:

string s = string.Join(" or ",
           from key in unValidatedFeedersOnMachine.Keys
           select "CompID = '" + reelid + "'");

或者更好,如果这是 SQL - 切换到 IN...

string s = "CompID IN (" + string.Join(","
           from key in unValidatedFeedersOnMachine.Keys
           select "'" + reelid + "'") + ")";

关于c# - 是否可以在迭代 ICollection 时确定当前位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4710995/

相关文章:

c# - 在文本文件中搜索字符串及其上一句和下一句

c# - 在 Visual Studio Community 2015 RC 中编译 VSIX 项目时出现问题

c# - 为 WPF 动画制作 C# 库线程安全

c# - 我是否应该在实现INotifyPropertyChanged的大量对象上遇到性能问题?

c# - .net 中的逻辑核心编程

c# - 在 C# 中从 HTML 表中检索数据

.net - DataTable 主键上区分大小写的字符

c# - Silverlight 还是 WPF?

c# - 在 .NET 4 下运行的 .NET 2 和 .NET 4 程序集之间有什么区别

c# - 将完整的子表单传递给另一个子表单