snippetcsharpMinor
Convert looping statement to linq mode
Viewed 0 times
loopinglinqstatementconvertmode
Problem
I have a model object class like this
And I am using it to hold some data like this
Later I want to preform some operations on this.
For example, I want to check if any of the resulting objects contain a specific
Now I wonder: Is this the most elegant way to do this? Maybe I don't even want to use a
Can any one tell me how I can modify this code so that it uses LINQ and lambda expressions?
public class EventInterestsResponse
{
public string id { get; set; }
public int sortOrder { get; set; }
public string name { get; set; }
public string categoryName { get; set; }
public string categoryId { get; set; }
}And I am using it to hold some data like this
public List GetEventInterests()
{
_data = _rh.ExecuteGetRequest();
var yourObject = _data != null ? (List)jsonSerializer.Deserialize>(_data) : null;
return yourObject;
}Later I want to preform some operations on this.
For example, I want to check if any of the resulting objects contain a specific
categoryId and if yes, I want to print it. I have written this working code:foreach (var interest in InterstList)
{
if (interest.categoryId == "11")
{
Branche:@interest.name
}
if (interest.categoryId == "22")
{
Udviklingsstadie:@interest.name
}
}Now I wonder: Is this the most elegant way to do this? Maybe I don't even want to use a
foreach loop. Can this be achieved by LINQ and using lambda expressions?Can any one tell me how I can modify this code so that it uses LINQ and lambda expressions?
Solution
I'm not sure if this is any better and it might depend on how many if statements or different categories you have whether it's worth it. But an alternative could be something like:
var categoryLabelValues = new Dictionary()
{
{"11", "Branche"},
{"22", "Udviklingsstadie"}
};
foreach(var interest in InterstList
.Where(p => categoryLabelValues.ContainsKey(p.categoryId)))
{
@categoryLabelValues[interest.categoryId]:@interest.name
}Code Snippets
var categoryLabelValues = new Dictionary<string, string>()
{
{"11", "Branche"},
{"22", "Udviklingsstadie"}
};
foreach(var interest in InterstList
.Where(p => categoryLabelValues.ContainsKey(p.categoryId)))
{
<strong>@categoryLabelValues[interest.categoryId]:@interest.name</strong>
}Context
StackExchange Code Review Q#40245, answer score: 4
Revisions (0)
No revisions yet.