您可以这样做的一种方法是将最长的行及其索引存储在字典中。从一个临时变量开始保存最长的行,然后遍历数组。当我们找到长度相等的行时,将它们添加到我们的字典中。如果我们找到更长的行,请将字典设置为新的,仅添加该行,然后继续。
例如:
public static void PrintLongestLinesAndIndexes(string[] input)
{
if (input == null)
{
Console.WriteLine("No data");
return;
}
var longestLine = string.Empty;
var longestLines = new Dictionary<int, string>();
for (int i = 0; i < input.Length; i++)
{
// If this line is longer, reset our variables
if (input[i].Length > longestLine.Length)
{
longestLine = input[i];
longestLines = new Dictionary<int, string> {{i, input[i]}};
}
// If it's the same length, add it to our dictionary
else if (input[i].Length == longestLine.Length)
{
longestLines.Add(i, input[i]);
}
}
foreach (var line in longestLines)
{
Console.WriteLine($"'{line.Value}' was found at index: {line.Key}");
}
}
那么我们可以像这样使用它:
public static void Main(string[] args)
{
PrintLongestLinesAndIndexes(new[]
{
"one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten"
});
GetKeyFromUser("\nDone! Press any key to exit...");
}
输出
另一种方法是使用Linq 选择项目及其索引,按项目的长度对它们进行分组,然后按长度对它们进行排序并选择第一组:
public static void PrintLongestLinesAndIndexes(string[] input)
{
Console.WriteLine(string.Join(Environment.NewLine,
input.Select((item, index) => new {item, index})
.GroupBy(i => i.item.Length)
.OrderByDescending(i => i.Key)
.First()
.Select(line => $"'{line.item}' was found at index: {line.index}")));
}