C#返回具有匹配属性的对象的列表

问题描述

我有以下对象:

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)) 

我想从此列表中选择一组字符串(颜色+大小),这些字符串存在于列表中的多辆汽车中

不知道该如何继续使用linq,因为我一直对此深感不安

解决方法

var groupedCars = list.
    GroupBy(c => c.color + c.size,c => c).
    Where(g => g.Count() > 1);
,

您应该先用/* Poetry In Motion; Cortez Phenix This program allows the user to make a poem,and the program contains a poem game. The most notable features are loops controlled by the user. */ #include <string> #include <iostream> using namespace std; void makePoem() { string poem; string user_input; cout << "Enter a poem of your own creation,one line at a time.\n"; cout << "Type 'quit' to exit the program.\n\n"; cout << "Type your poem,pressing the enter key to create a new line.\n\n"; while (getline(cin,user_input)) { if (user_input == "quit") break; poem += user_input; poem += '\n'; } cout << "\nGoodbye! Have a great day.\n"; } int main() { makePoem(); return 0; } color group the list,然后选择size大于1的项目

Count

此外,您应将var result = list .GroupBy(c => string.Join(c.color,c.size)) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToList(); color标记为size字段(或使用属性,这是更好的选择)