数据集中的数据比较

时间:2012-03-03 21:37:03

标签: linq dataset

我必须编写一个执行以下操作的方法: 有一个DataSet假设CarDataSet有一个表Car,包含主键ID和另外一列ColorId。并且有一个字符串,其中Ids用逗号分隔,例如“5,6,7,8”(随机长度)。任务是检查给定的Car Ids是否所有合适的ColorId都相同。

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;

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

2 个答案:

答案 0 :(得分: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);

编辑或者,如果在没有给定ID的汽车时抛出异常没有问题,可以在lambda语法中使用两个查询:

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

答案 1 :(得分:1)

您可以通过执行distinct来执行此操作,并断言计数为1。

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