简体   繁体   English

如何比较两个列表,如果它们具有相等的值,则取列表的两个索引

[英]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.两个列表都有同样多的值,应该比较的两个列表中都有 id,另外两个应该写出值的列表中都有 categoryNames。 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.如果您愿意,可以查看LinQ ,尤其是WhereDistinct扩展方法。

I hope I was useful.我希望我有用。

You can retrieve matching elements with .Intersect() , then use .IndexOf() to get the indexes.您可以使用.Intersect()检索匹配元素,然后使用.IndexOf()获取索引。 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 :您可以从列表之一创建Dictionary<T, int[]> ,例如从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现在,在dict.TryGetValue的帮助下,您可以获得所需值出现在list2所有int[]索引,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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