user9704250
user9704250

Reputation:

Conditionally map a new property in LINQ based on another value

I'm new in LINQ, I have the following 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();

I want to add extra field call it (color),and have the following conditions:

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

Upvotes: 0

Views: 939

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460148

You can use:

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;
}

Or use a Dictionary<string, string> as mapping.

Upvotes: 0

StuartLC
StuartLC

Reputation: 107267

Since you've already materialized your data with .AsEnumerable(), you'll be able to provide any arbitrary mapping function taking the grouping key and mapping it to a colour.

If performance is important, I would suggest however that you move the mapping into a static Dictionary at class scope, along the lines of:

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

Which you can then use in your projection like so:

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

One caveat : You may need to be wary and guard against attempting to map an item which isn't in the dictionary, as this would result in a KeyNotFoundException.

Upvotes: 0

Hasan Gholamali
Hasan Gholamali

Reputation: 633

Use inline condition statement like below:

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

Upvotes: 1

Related Questions