Reputation: 4480
I am using below LINQ Query, now i want to if else condition inside LINQ Query like below- how i can achieve the same ?
if(stemming)
highlightedText = c.Value.p_content != null && c.Value.p_content[0] != null ? c.Value.p_content[0] : string.Empty
if(phoentic)
highlightedText = c.Value.s_content != null && c.Value.s_content[0] != null ? c.Value.s_content[0] : string.Empty
if(content)
highlightedText = c.Value.content != null && c.Value.content[0] != null ? c.Value.content[0] : string.Empty
Complete code -
var highlightedDataLst = objJson.highlighting.Select(c =>
new finalOutput
{
highlightedKey = c.Key,
highlightedText = c.Value.content != null && c.Value.content[0] != null ? c.Value.content[0] : string.Empty
}).ToList<finalOutput>();
Upvotes: 2
Views: 1640
Reputation: 5395
Hmm taking a stab at it, it might look something like this:
var highlightedDataLst = objJson.highlighting.Select(c =>
new finalOutput
{
highlightedKey = c.Key,
highlightedText = (stemming ? c.Value.p_content?[0] :
(phoentic ? c.Value.s_content?[0] :
(content ? c.Value.content?[0] : null))) ?? ""
}).ToList<finalOutput>();
You can simplify your conditions using the null conditional operator (?[]) and null coalescing operators (??).
Upvotes: 2