2012-03-03 88 views
0

我必须编写一个可以执行以下操作的方法: 有一个DataSet让我们说CarDataSet带有一个表Car,并且包含主键Id和一个更多列ColorId。还有一个字符串,用逗号分隔,例如“5,6,7,8”(随机长度)。任务是检查给定的汽车ID是否所有适当的ColorIds是相同的。数据集中的数据比较

For example: 
String ids = "5,6,7,8" 
If all the Cars ColorIds are for example 3,3,3,3 where the Car Ids are 5,6,7,8 then return true; 

换句话说 - 检查所有具有给定Ids的汽车是否使用同一种颜色。现在我没有我的代码了,但是我使用了3个foreach循环和3个linq表达式。有没有更简单的方法可以做到这一点?

回答

1

如果你希望所有的汽车都有相同的颜色是指所有的人都应该有相同的颜色,第一个:

// first find the cars with given ids 
var selectedCars = Cars.Where(x=>ids.Contains(x.ID.ToString()); 
// select one of them as comparer: 
var firstCar = selectedCars.FirstOrDefault(); 
if (firstCar == null) 
    return true; 
// check all of them has same color as first one: 
return selectedCars.All(x=>x.ColorID == firstCar.ColorID); 

编辑:或者,如果你有抛出异常的时候没有车,没有问题给IDS可以使用两种查询在lambda语法:

var selectedCars = Cars.Where(x=>ids.Contains(x.ID.ToString())); 
return selectedCars.All(x=>x.ColorID == selectedCars.First().ColorID); 
1

你可以通过执行不同的,并且断言计数做,这是1

var colors = Cars.Where(x=>ids.Contains(x.ID.ToString()) 
        .Select(x=>x.ColorID) 
        .Distinct().Count(); 
return count == 1; 
+0

字符串本身有Contains方法,不需要创建另一个数组。 – 2012-03-04 10:39:42