none
Simplify if else using LINQ RRS feed

  • Question

  • Hi,

    I have code like this

    private List<NetworkPlanNodesModel> GetNodes(int resourceId) { var nodes = new List<NetworkPlanNodesModel>(); var group = String.Empty; foreach (var resource in this.resourceNodes) { if (resource.Id == resourceId) { group = NetworkPlanModel.ResourceGroup; } else { group = NetworkPlanModel.FilterResourceGroup; }

    }

    return nodes; }

    Instead using if else, would it be possible that I am using any LINQ Operator?

    Thanks :)





    • Edited by wapt49 Friday, October 24, 2014 3:40 PM
    Friday, October 24, 2014 3:17 PM

Answers

All replies

  • You realise you don't do anything at all to add to nodes or with group?

    And where's Networkplanmodel come into it?

    Friday, October 24, 2014 3:23 PM
    Moderator
  • Hi,

    After foreach I need to do some operation with group, but I just simplify it.. So I just remove it. My question actually is it possible to  change this if else operator at this context using LINQ operator?

    if (resource.Id == resourceId)
    {
         group = NetworkPlanModel.ResourceGroup;
    }
    else
    {
         group = NetworkPlanModel.FilterResourceGroup;
    }  

    Regards

    Friday, October 24, 2014 3:44 PM
  • The idea is to check whether there is a matching entry in the list and set group to resourcegroup if there is one?

    if(resourceNodes.Any(x => x.id == resourcid))
    {
    	group = NetworkPlanModel.ResourceGroup;
    }
    else
    {
    	group = NetworkPlanModel.FilterResourceGroup;
    }

    Friday, October 24, 2014 6:12 PM
    Moderator
  • Hi,

    Someone has answer my question, but I don't know why he deleted his post. The answer looks like this

    var group = resourceNodes.Any(r => r.Id == resourceId) ? NetworkPlanModel.ResourceGroup : NetworkPlanModel.FilterResourceGroup;

    But it's my bad. I think I don't need LINQ for this.. I just need use ternary operator to simplify the operation

    foreach (var resource in this.resourceNodes)
    {               
         var group = resource.Id == resourceId ? NetworkPlanModel.ResourceGroup : NetworkPlanModel.FilterResourceGroup; 
    }

    So, I think for my first above question solved.

    • Edited by wapt49 Friday, October 24, 2014 7:48 PM
    • Marked as answer by wapt49 Friday, October 24, 2014 7:49 PM
    Friday, October 24, 2014 7:46 PM
  • You realise that will produce a different result?

    Saturday, October 25, 2014 12:30 PM
    Moderator
  • No, which one do you mean?
    Tuesday, October 28, 2014 11:15 AM