How does LINQify do this?

Is there a way to clear this type of loop using LINQ?

  List<Car> result;
  List<string> makes;
  List<string> models;

  for (int i = 0; i < makes.Count() && i < models.Count(); i++)
  {
    result.Add(new Car() { Make = makes[i], Model = models[i] });
  }

Basically I am looking for a way to map multiple arrays of individual fields into a single array of objects consisting of these fields.

+3
source share
4 answers

You can use Enumerable.Range, for example:

List<Car> result = Enumerable.Range(0, Math.Min(makes.Count, models.Count))
    .Select(i => new Car { Make = makes[i], Model = models[i] }).ToList();

If makesthey modelsalways contain the same number of elements, you can use a more compact syntax:

List<Car> result = makes.Select((make, i) => new Car { Make = make, Model = models[i] }).ToList();
+7
source

Looks like you really need a new LINQ statement - one that wasn't included in LINQ, somewhat by accident: Zip. This will basically take two enumerated numbers and return one enumerated one that joins the records until one or the other of the original sequences ends.

, , . :

List<Car> cars = makes.Zip(models)
                      .Select(pair => new Car(pair.First, pair.Second))
                      .ToList();

, , MiscUtil.

+4

, LINQ , , IEnumerable<Car>. :

IEnumerable<Car> cars = new MyClass(makes, models);
var result = from cars...

; (, , ), ( IEnumerator<Car>).

This approach does not allow you to embed implementation details in all your LINQ queries. Also, if you have never done this, this is really something worth learning. Convenient implementation IEnumerable<T>greatly expands the space of things with which you can easily use LINQ for.

+1
source
List<Car> result = makes
                   .Take(model.Count)
                   .Select((make, index) => new Car {Make = make, Model = models[index]});

Note that this works even if make and models do not have the same length.

+1
source

Source: https://habr.com/ru/post/1698044/


All Articles