-1

I have the following Objects:

class Car{
   int price;
   string color;
   string size;
}

var list = new List<Car>();
list.Add...//add 20 cars

//I now want to select from this list any cars whose color and size matches that of any other car

list.Select(car => String.Join(car.color, car.size)) 

I want to select from this list a set of strings (color + size) which are present in more than one car in the list

Not sure where to continue with linq, as I've been banging my head into this for a bit

Papi Abi
  • 49
  • 1
  • 4
  • Do you want the result to be a List of the Car instances meeting the criteria, or a List of the color+size strings of the cars meeting the criteria? – Paul Pearce Oct 14 '20 at 20:36
  • Your question isn't entirely clear, but it seems you want combinations of "color" and "size", and then to produce all of the sets for which there is more than one match. See `GroupBy()`; in particular, group on a proper key (not the examples shown in the very poor answers below), and then return only those groups where the count of the elements in the group is greater than one. See duplicate for grouping. – Peter Duniho Oct 14 '20 at 20:41

2 Answers2

1
var groupedCars = list.
    GroupBy(c => c.color + c.size, c => c).
    Where(g => g.Count() > 1);
Joel Coehoorn
  • 362,140
  • 107
  • 528
  • 764
1

You should group the list by color and size first, then select items whose Count greater then 1

var result = list
    .GroupBy(c => string.Join(c.color, c.size))
    .Where(g => g.Count() > 1)
    .Select(g => g.Key)
    .ToList();

Also, you should mark color and size as public fields (or use properties, which is better option)

Pavel Anikhouski
  • 18,232
  • 12
  • 32
  • 48