-1

在下面的代码中,我必须比较两个字符串,但我必须保留原始数组的索引。有没有办法做到这一点?

代码 :

        private dataStruct[] compare(string[] older, string[] new_str)
        {
            List <dataStruct> diff = new List<dataStruct>();

            foreach (var str in older.Except(new_str))
            {
                Console.WriteLine(str);
            }
            return diff.ToArray();
        }

实际输出:第 1 行第 3 行...

预期输出:[1]=>第 1 行 [3]=>第 3 行...

谢谢!

4

2 回答 2

1

这很好地做到了:

foreach ((var str, var n) in older.Select((x, n)=> (x, n)).Where(z => !new_str.Contains(z.x)))
{
    Console.WriteLine($"[{n + 1}]=>{str}");
}

当我使用此代码进行测试时:

compare(new [] { "A", "B", "D", "C", "E" }, new [] { "B", "C", "E" });

我得到:

[1]=>A
[3]=>D
于 2020-11-18T22:43:49.147 回答
-2

foreach 不跟踪索引,这就是 for 循环的用途。

我想它会导致这样的事情:

private static dataStruct[] compare(string[] older, string[] new_str)
{
     int length = older.Length > new_str.Length ? older.Length : new_str.Length;

     List<dataStruct> diff = new List<dataStruct>();

     for (int index = 1; index <= length; index++)
     {
         string oldItem = index < older.Length ? older[index].oldItem : "N/A";
         string newItem = index < new_str.Length ? new_str[index].oldItem : "N/A";
                
         if (oldItem != newItem)
         {
             Console.WriteLine(string.Format("ID = [{0}]\t=>\t Old : {1}\t new : {2}", index, oldItem,newItem));
             diff.Add(new dataStruct(index, oldItem, newItem));
         }
     }

     return diff.ToArray();
}

struct dataStruct
{
    public int index { get; }
    public string oldItem { get; }
    public string newItem { get; }

    public dataStruct(int index, string oldItem, string newItem)
    {
        this.index = index;
        this.oldItem = oldItem;
        this.newItem = newItem;
    }
}
于 2020-11-18T22:06:30.457 回答