可能重复:
(C#)获取当前foreach迭代的索引
早上好,
有没有办法Enumerator在不使用辅助变量的情况下获取当前元素的索引(在这种情况下,是字符串中的字符)?我知道如果我使用一个while或者forcicle,这可能会更容易,但使用枚举器循环一个字符串更优雅......这个案例的唯一缺点是我真的需要得到每个字符的当前索引.
非常感谢你.
我正在学习 C#,并且参加了很多在线课程。我正在寻找一种更简单/更简洁的方法来枚举列表中的列表。
在 python 中,我们只需一行即可完成类似的操作:
newListofList=[[n,i] for n,i in enumerate([List1,List2,List3])]
Run Code Online (Sandbox Code Playgroud)
C#中一定要涉及lambda和Linq吗?如果是这样,解决办法是什么?我在 C# 中尝试使用 Dictionary,但我的直觉告诉我这不是一个完美的解决方案。
List<List<string>> familyListss = new List<List<string>>();
familyListss.Add(new List<string> { "Mary", "Mary_sister", "Mary_father", "Mary_mother", "Mary_brother" });
familyListss.Add(new List<string> { "Peter", "Peter_sister", "Peter_father", "Peter_mother", "Peter_brother" });
familyListss.Add(new List<string> { "John", "John_sister", "John_father", "John_mother", "John_brother" });
Dictionary<int, List<string>> familyData = new Dictionary<int, List<string>>();
for (int i = 0; i < familyListss.Count; i++)
{
familyData.Add(i, familyListss[i]);
}
Run Code Online (Sandbox Code Playgroud) 有没有办法知道当前的foreach运行,而不必:
Int32 i;
foreach
i++;
Run Code Online (Sandbox Code Playgroud)
或者这是我得到的最佳选择?另外,我怎么知道该循环中的最大项目数?我想要做的是在表单上的foreach循环期间更新进度条.
这是我到目前为止:
FileInfo[] directoryFiles = (new DirectoryInfo(folderBrowserDialog.SelectedPath)).GetFiles("*.*");
foreach (FileInfo file in directoryFiles)
{
if ((file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden || (file.Attributes & FileAttributes.System) == FileAttributes.System)
continue;
backgroundWorkerLoadDir.ReportProgress(i, file.Name);
System.Threading.Thread.Sleep(10);
}
Run Code Online (Sandbox Code Playgroud)
所以它应该如下,对吧?
for (Int32 i = 0; i < DirectoryFiles.Length; i++)
{
if ((DirectoryFiles[i].Attributes & FileAttributes.Hidden) == FileAttributes.Hidden || (DirectoryFiles[i].Attributes & FileAttributes.System) == FileAttributes.System)
continue;
backgroundWorkerLoadDir.ReportProgress((i / DirectoryFiles.Length) * 100, DirectoryFiles[i].Name);
System.Threading.Thread.Sleep(10);
}
Run Code Online (Sandbox Code Playgroud) 在foreach循环中,我想比较一个元素与之前读取的元素.我怎样才能做到这一点?在foreach循环中寻址前一个元素的语法是什么?
谢谢!
我有以下问题.分裂之后我想把作者,标题和booktype变成这样的变量.
string author = George Orwell
string title = Animal Farm
string booktype = novel
Run Code Online (Sandbox Code Playgroud)
使用foreach循环打印它们很容易,但我如何获得这些值?希望有人能帮助我.
static void Main(string[] args)
{
string[] book = new string[12];
book[0] = "George Orwell###Animal Farm###Novel###";
string value = book[0];
string[] item = Regex.Split(value, "###");
foreach (string newItem in item)
{
Console.WriteLine(newItem);
}
// prints out just fine
// George Orwell
// Animal Farm
// Novel
Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)