c# - LINQ to check each property of a list object to see if it's value is equal to a string -


i have list object contains positions properties in object. want check see if of these properties equal string (ie, "starter"). how can via linq without having check each position individually?

for instance if have 18 positions properties of list item, , qb, rb , wr have value "starter" want positions returned in linq query.

example:

public class teamneeds {    public string qb {get; set;}    public string rb {get; set;}    public string wr {get; set;}    public string te {get; set;}   .......etc, etc }   list<teamneeds> needs = new list<teamneeds>(); 

i pull in info datatable team, there various things each position---starter, backup, depth, etc...

in instance want find positions within list having "starter" value(ie, loop through properties of list item find properties values = "starter")

here's methodology using reflection:

class program {     static void main(string[] args)     {         list<teamneeds> needs = new list<teamneeds>();          teamneeds n1 = new teamneeds();          n1.qb = "starter";          teamneeds n2 = new teamneeds();          n2.rb = "starter";          needs.add(n1);         needs.add(n2);          foreach (var need in needs)         {             ienumerable<propertyinfo> list = need.gettype().getproperties().where(prop => (string)prop.getvalue(need, null) == "starter");             foreach (var item in list)             {                 //this give propertyname                 console.writeline(item.name);             }         }         console.readline();     } } public class teamneeds {     public string qb { get; set; }     public string rb { get; set; }     public string wr { get; set; }     public string te { get; set; } } 

however, design work better you:

class program {     static void bettermain(string[] args)     {         list<teamv2> teamlist = new list<teamv2>();          foreach(var team in teamlist)         {             list<player> starters = team.playerlist.where(p => p.isstarter == true).tolist();             starters.foreach(p => console.writeline(p.positionname));         }             } }  public class teamneeds {     public string qb { get; set; }     public string rb { get; set; }     public string wr { get; set; }     public string te { get; set; } }   public class teamv2 {     public list<player> playerlist = new list<player>(); }  public class player {     public bool isstarter;     public bool positionname; } 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -