Home > Software engineering >  c# compare array of string and array of type
c# compare array of string and array of type

Time:12-02

I have two arrays.

Structure for first array1:

["A", "B", "C", "D", "E"]

Structure for second array2:

It is a List of Type

Type
    [0]
       firstName: "A"
       lastName: "Sam"
    [1]
       firstName: "B"
       lastName: "Mark"
    [2]
       firstName: "X"
       lastName: "Steve"
    [3]
       firstName: "E"
       lastName: "Mike"

I want to compare both the arrays and return lastName when array1 and array2 match with firstName. So the output will be something like this.

["Sam", "Mark", "Mike"]

CodePudding user response:

You can use LINQ to get the values you need

List<string> result = array2.Where(x => array1.Contains(x.firstName))
                            .Select(x => x.lastName).ToList();

What this does is.. filters the array2 to only the Type's firstName that match up with array1 and then selects the last names from that matched list.

  •  Tags:  
  • c#
  • Related