Home > front end >  Compare two Lists and pass to another
Compare two Lists and pass to another

Time:12-31

I have two List<Int64> ListA contains 10 digits of integer value and ListB contains 6 digits of integer, I have to compare both lists and pass to another List<int64> if ListA contains 6 digits from ListB.

CodePudding user response:

public static void Main(string[] args)
{
    var listA = new List<long>
    {
        1, 2, 3, 4, 5, 6
    };
    var listB = new List<long>
    {
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    };

    bool doesListBContainListA = listA.All(numA => listB.Contains(numA));
    var listNew = new List<long>();
    if (doesListBContainListA)
    {
        listNew.AddRange(listA);
        listNew.AddRange(listB);
    }

    Console.WriteLine(string.Join(", ", listNew));
}

The above code will compare if all digits/numbers from listA are contained in listB and if they are they will be added to the new list.

P.S. long is the same as Int64

CodePudding user response:

Seems to me like you should be using linq's Intersect method:

var listA = new List<long> {0,1,2,3,4,5,6,7,8,9};
var listB = new List<long> {0,2,4,6,8};
var numbersInBoth = listA.Intersect(listB).ToList();

The numbersInBoth variable will be an instance of List<long> that contains only the numbers that both lists have.

  • Related