Abhilash J A

Abhilash J A

  • 528
  • 2.4k
  • 602.7k

list object if contain one value then return another one c#

Dec 23 2016 5:29 AM
Hello,
 
I have list items
The Priority list's object may contain 1 or 2 or 3.
 
If Priority contain 1 then return "Low"
If Priority contain 2 then return "Medium"
If Priority contain 3 then return "High"
 
I have tried... 
  1. public class DocumentsUser  
  2.     {  
  3.   public string Priority { getset; }  
  4. }  
  5.   
  6. List<DocumentsUser> objUserSetUp = objUserSetUp1.Select(m => new DocumentsUser()  
  7.                 {   
  8.  Priority = m.Priority == 3 ? "High" : "Low"//Here I want to manage that contition.  
  9. }  
 How can I do that?

Answers (5)

1
Ujjwal Gupta

Ujjwal Gupta

  • 0
  • 1.1k
  • 457.6k
Dec 23 2016 5:54 AM
  1. public class DocumentsUser    
  2.     {    
  3.   public string Priority { getset; }    
  4. }    
  5.     
  6. List<DocumentsUser> objUserSetUp = objUserSetUp1.Select(m => new DocumentsUser()    
  7.                 {     
  8.  Priority = GetPriority(m.Priority);  
  9. }  )  
  10.   
  11. public string GetPriority(int priority)  
  12. {  
  13.     switch(priority)  
  14.     {  
  15.         case 1:return "Low";break;  
  16.         case 2:return "Medium";break;  
  17.         case 3:return "High";break;  
  18.         Default:return "Low";break;  
  19.     }  
  20. }  
Accepted Answer
1
Nitin Sontakke

Nitin Sontakke

  • 135
  • 13.6k
  • 14.9k
Dec 24 2016 1:47 AM
@Fabio,
 
Agreed in principle. However, just for record, specific to xml serialization, enum values can be decorated with an attribute as follows:
 
[XmlEnum(Name="High")]
 
 
1
Fabio Silva Lima

Fabio Silva Lima

  • 0
  • 4.2k
  • 1.2m
Dec 23 2016 9:37 AM
@Nitin I agree but it depends what he is trying to do. He can face a serialization problem with enum. If the frontend expects an integer when we use enum it's serialize as string and other problems with database.
 
@Ujjwal I do not like to use switch because a new priority you will need to add one more case. But i liked you separate method for the conversion.
1
Nitin Sontakke

Nitin Sontakke

  • 135
  • 13.6k
  • 14.9k
Dec 23 2016 9:24 AM
Even better approach would be to have a property of enum's type as:
 
public PriorityType Priority {get; set;} 
 
 
1
Fabio Silva Lima

Fabio Silva Lima

  • 0
  • 4.2k
  • 1.2m
Dec 23 2016 5:35 AM
create a enum and convert Priority.
 
  1. public class DocumentsUser    
  2.     {    
  3.   public string Priority { getset; }    
  4. }    
  5.   
  6. public enum PriorityType{  
  7.  High = 3,  
  8.   Medium = 2,  
  9.   Low = 1  
  10. }  
  11.     
  12. var objUserSetUp = objUserSetUp1.Select(m => new {Priority = (PriorityType)m.Priority});