HelloWorld1
HelloWorld1

Reputation: 14108

Compare two different lists

I have rephased my message with explicit question.

I have two different list.

List<Car> car = GetCars();
List<int> carListNumber = new List<int> { 1, 2, 3};

public Car
{
    public int number
    public string color
    public string brand
}

My request is to achieve a new Car list that shall contain number 1,2,3 based on LinQ coding?

In order to get this specific car you have to recieve right car number from carListNumber.

Upvotes: 2

Views: 810

Answers (4)

Jonathan Stanton
Jonathan Stanton

Reputation: 2630

To get a List<int> of the cars numbers from the List<Car> try the following:

var listOfCarNumbers = car1.Select(car=>car.number).ToList();
var listsMatches = listOfCarNumbers.TrueForAll(carListNumber.Contains) && listOfCarNumbers.TrueForAll(carListNumber.Contains);

ListsMatches then contains a boolean value if the 2 match.

Upvotes: 0

niemiro
niemiro

Reputation: 1838

Need to have a list of the number 1, 2 and 3 from Car's number based on LinQ or similiar.

How shall I do to compare two different list with different context?

So you want to take a car from the list, say BMW, and find out it's number?

I really struggle to understand quite what you want to do. You can address a List with an index. Will that help?

EDIT out the below:

Finally understood what you want to do. Do you want the order of cars to be driving, or the order of numbers? If you have BMW2, Audi1, do you want the number order to be 2, 1, or the car order to be Audi, BMW. Then I will help with the code :)

List<Car> car1 = GetCars1();
int number = car1.IndexOf(//car//);

If you need any more help, can you please re-explain your question, and also, could you please do us a big favour, and mark/up-vote suitable answers in your previous questions.

Thanks so much!

Upvotes: 0

John Saunders
John Saunders

Reputation: 161773

carListNumber.SequenceEquals(car1.Select(car=>car.number));

Upvotes: 5

Axarydax
Axarydax

Reputation: 16603

bool listsAreTheSame(List<Car> cars, List<int> numbers){
  if(cars.Count() != numbers.Count())
    return false;
  for(int  i = 0; i < cars.Count(); i++){
    if(cars[i].number != numbers[i])
      return false;
    }
  return true;
}

Upvotes: 0

Related Questions