有条件地根据另一个值在LINQ中映射新属性

时间:2018-05-23 12:00:00

标签: c# linq

我是LINQ的新手,我有以下LINQ:

 var number_ofCPtype = (from DataRow s in resultFaultCrewprCurrent[1].AsEnumerable()
       group s by s.Field<string>("cp_type") into g
       select new
       {
           mm = g.Key ,
           list = g.Count()
       }).ToList();

我想添加额外的字段调用它(颜色),并具有以下条件:

  if (g.key=="Stiven")
    color ="blue"
  if(g.key=="Alex")
    color ="red"
  if(g.key=="Jack")
    color ="green"

3 个答案:

答案 0 :(得分:1)

您可以使用:

var query = from row in resultFaultCrewprCurrent[1].AsEnumerable()
            group row by s.Field<string>("cp_type") into typeGroup
            select new {
               mm = typeGroup.Key ,
               list = typeGroup.Count(),
               color = GetColor(typeGroup.Key) 
            };
var number_ofCPtype = query.ToList();
string GetColor(string name)
{
   string color;
   if (name == "Stiven")
     color = "blue";
   else if(name == "Alex")
     color = "red";
   else if(name == "Jack")
     color = "green";
   else
     color = defaultColor; // TODO
   return color;
}

或使用Dictionary<string, string>作为映射。

答案 1 :(得分:1)

使用如下所示的内联条件声明:

var number_ofCPtype = (from DataRow s in resultFaultCrewprCurrent[1].AsEnumerable()
                       group s by s.Field<string>("cp_type") into g
                       select new
                       {
                           mm = g.Key ,
                           list = g.Count(),
                           color = (g.key == "Stiven" ? "blue" : (g.key=="Alex" ? "red" : (g.key=="Jack" ? "green" : "undefined")) )
                       }).ToList();

答案 2 :(得分:1)

由于您已经使用.AsEnumerable()实现了数据,因此您可以使用分组键并将其映射为颜色来提供任意映射功能。

如果性能很重要,我建议您将映射移动到类范围内的静态Dictionary,方法如下:

private static readonly Dictionary<string, string> MyColourMap 
= new Dictionary<string, string>
{
   ["Stiven"] = "blue",
   ["Alex"] = "red",
   ["Jack"] = "green"
};

然后您可以在投影中使用:

select new
{
  mm = g.Key,
  list = g.Count(),
  color = MyColourMap[g.Key] // Lookup the corresponding value
})
.ToList();

有一点需要注意:您可能需要谨慎并guard against attempting来映射字典中不存在的项目,因为这会产生KeyNotFoundException