简体   繁体   中英

How to compare two lists and if they have an equal value take the two indexes of the lists

How would you go about comparing two lists and saying that if these two lists have an equal value take index of the two different spots and spit out two other list values from two different lists at that index. Both lists have equally as many values both of the lists that should be compared have ids in them and the other two that are supposed to write out value have categoryNames in them. My code looks like this...

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;

namespace PrestaConverter
{
    public class ExcellCreation
    {
        #region privata variabler

        /// <summary>
        /// WhatExcelFile Håller reda på Vilken excelfil som ska sparas, 
        /// Name Namnet på sparfilen,
        /// count är en räknare som ger id till Kategorierna
        /// </summary>
        Hashtable myHashtable = new Hashtable();
        private int WhatExcellFile;
        private string name = "CategoriesCatalog";
        private List<string> ColumnNames = new List<string>() {"ID",
            "Active(0/1)",
            "Name*",
            "Parent Category",
            "Root Category(0/1)",
            "Description",
            "Meta title",
            "Meta keywords",
            "Meta description",
            "URL rewritten",
            "Image URL"
        };
        private Categories categories1 = new Categories();
        private Categories categories2 = new Categories();
        private Categories categories3 = new Categories();
        private int count;
        ExcelConverter converter = new ExcelConverter(); 

        #endregion

        #region Skapa excel

        /// <summary>
        /// Funktion som skapar de nya Excelfilerna 
        /// </summary>
        /// <param name="excelValue">Kategorinamnen sänds över till denna funktion för upplägg i ny fil</param>
        /// <param name="rowAmmount">Används till att få tag på hur många rader som ska existera i excel filen</param>
        /// <returns></returns>
        public string CreateExcel(List<Categories> categories)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                return "Excel är inte korrekt installerat";
            }

            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            categories1 = categories[0];
            categories2 = categories[1];
            categories3 = categories[2];

            for(int i = 0; i < categories1.CategoryId.Count; i++)
            {
                if(categories1.NewCategoryId.Contains(categories1.CategoryId[i]) == false && categories1.CategoryId[i].Substring(3,4) == "0000")
                {
                    categories1.NewCategoryId.Add(categories1.CategoryId[i]);
                    categories1.NewCategoryName.Add(categories1.CategoryName[i]);
                }
            }
            Console.WriteLine(categories1.NewCategoryId.Count); 
            for(int i = 0; i < ColumnNames.Count; i++)
            {
                xlWorkSheet.Cells[1, i + 1].Value2 = ColumnNames[i];
            }
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[2 + i , 3].Value2 = categories1.NewCategoryName[i];
                xlWorkSheet.Cells[2 + i, 4].Value2 = "Home";
            }
            for(int i = 0; i < categories2.CategoryId.Count; i++)
            {
                if(categories2.NewCategoryId.Contains(categories2.CategoryId[i]) == false && categories2.CategoryId[i].Substring(5, 2) == "00")
                {
                    categories2.NewCategoryId.Add(categories2.CategoryId[i]);
                    categories2.NewCategoryName.Add(categories2.CategoryName[i]);
                }
            }

            Console.WriteLine(categories2.NewCategoryName.Count); 
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                for(int j = 0; j < categories2.NewCategoryId.Count; j++)
                {
                    if(categories1.NewCategoryId[i].Substring(0,3) == categories2.NewCategoryId[j].Substring(0, 3))
                    {
                        categories2.parentCategoryId.Add(categories1.NewCategoryId[i]);
                        categories2.parentCategoryName.Add(categories1.NewCategoryName[i]);
                    } 
                }
            }
            for(int i = 0; i < categories2.parentCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 4].Value2 = categories2.parentCategoryName[i]; 
            }
            for(int i = 0; i < categories2.NewCategoryName.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 3].Value2 = categories2.NewCategoryName[i];
            }

            //Here saving the file in xlsx
            xlWorkBook.SaveAs(@"C:\Users\Jens Svensson\Documents\" + name + ".xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, misValue,
                misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

            xlWorkBook.Close(true);
            xlApp.Quit();

            return "Funkar";
        }

        #endregion

        private string createId(string Id, int start, int end)
        {
            return Id.Substring(start, end);
        }
    }
}

TestCode

    public List<string> NewCategoryId = new List<string>();
    public List<string> NewCategoryName = new List<string>();

    public List<string> parentCategoryId = new List<string>();
    public List<string> parentCategoryName = new List<string>();

    parentCategoryId = <"3930000", "3930000",4230000, 5200000 >
    parentCategoryName = <"Computers", "Computers", Toys, Furniture>

    NewCategoryId = <"3931200", "4231400","5201300" "3931700">
    NewCategoryName = <"Chairs","HP","ToyCars", "Lenovo">

    for(int i = 0; i < NewCategoryId.Count; i++){

       for(int j = 0; parentCategoryId.Count; j++){
           if(parentCategoryId[j] == NewCategoryId[i]){
               Console.Write(NewCategoryId[i] + "     ")
               Console.Write(NewCategoryName[i] + "     ")
               Console.Write(parentCategoryId[j] + "   " )
               Console.Write(parentCategoryName[j] + "\n")
           }
       }



    }


Wanted result
3931700 Lenovo  3930000 Computers
3931200 HP      3930000 Computers
4231400 Chairs  4230000 Furniture
5201300 ToyCars 5201300 Toys

This is an ish result that i whant but im just getting them scrambled so how to do this?

I did not understand quite well you're question. I looked at your code and it seems reasonable.

If you want you could take a look at LinQ , especially at the Where and Distinct extension mothods.

I hope I was useful.

You can retrieve matching elements with .Intersect() , then use .IndexOf() to get the indexes. Finally, access the index values of the other lists.

var list1 = new List<int> { 1, 2, 3, 4, 5 };
var list2 = new List<int> { 4, 5, 6, 7, 8 };

var intersectingValues = list1.Intersect(list2); // 4, 5
var interesectingValueIndexes = intersectingValues.Select(x => 
                                   new { I1 = list1.IndexOf(x), I2 = list2.IndexOf(x) });

var otherList1 = new List<string> { "a", "b", "c", "d", "e" };
var otherList2 = new List<string> { "f", "g", "h", "i", "j" };

var otherListIndexValues = interesectingValueIndexes.Select(x => 
                                   new { V1 = otherList1[x.I1], V2 = otherList2[x.I2] });

You can create a Dictionary<T, int[]> from one of the lists, say from list2 :

using System.Linq;

...

var list1 = ...
var list2 = ... 

var dict = list2
  .Select((value, index) => new {value, index})     
  .GroupBy(pair => pair.value, pair => pair.index)
  .ToDictionary(group => group.Key, group => group.ToArray());

Now, with a help of dict.TryGetValue you can get all the int[] indexes at which required value appears in list2 , eg

foreach (var item in list1) {
  if (dict.TryGetValue(item, out int[] indexes)) {
    // item appears in list2 at indexes
    Console.WriteLine($"value {item} appears at [{string.Join(", ", indexes)}]");
  }
  else {
    // item is not found in list2 
  }
}

Demo:

var list1 = new List<string>() {"A", "B", "C", "D", "E"};
var list2 = new List<string>() {"A", "B", "A", "A", "C", "B", "D"};

var dict = list2
  .Select((value, index) => new {value, index})     
  .GroupBy(pair => pair.value, pair => pair.index)
  .ToDictionary(group => group.Key, group => group.ToArray());

for (int i = 0; i < list1.Count; ++i) {
  var item = list1[i];

  if (dict.TryGetValue(item, out int[] indexes))
    Console.WriteLine(
      $"value {item} at {index} appears in list2 at [{string.Join(", ", indexes)}]");
  else 
    Console.WriteLine($"value {item} at {index} doesn't appear in list2");
}

Outcome:

value A at 0 appears in list2 at [0, 2, 3]
value B at 1 appears in list2 at [1, 5]
value C at 2 appears in list2 at [4]
value D at 3 appears in list2 at [6]
value E at 4 doesn't appear in list2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM