簡體   English   中英

C# : Array.Except,獲取該值在返回數組的原始數組中的索引

[英]C# : Array.Except, Getting the index the value had in the original array of the returned array

在下面的代碼中,我必須比較兩個字符串,但我必須保留原始數組的索引。 有沒有辦法做到這一點?

代碼 :

        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 行...

謝謝!

這很好:

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

foreach desn 不跟蹤索引,這就是 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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM