c# - Linq: Select object based on property -


how 1 select specific object using query-expression style linq?

private static observablecollection<branch> _branches = new observablecollection<branch>(); public static observablecollection<branch> branches {     { return _branches; } }  static void main(string[] args) {     _branches.add(new branch(0, "zero"));     _branches.add(new branch(1, "one"));     _branches.add(new branch(2, "two"));      string toselect="one";      branch thebranch = in branches                         let valuebranchname = i.branchname                         valuebranchname == toselect                         select i;      console.writeline(thebranch.branchid);      console.readline(); } // end main   public class branch{     public int branchid;     public string branchname;      public branch(int branchid, string branchname){         this.branchid=branchid;         this.branchname=branchname;     }      public override string tostring(){         return this.branchname;     } } 

returns following error:

error   1   cannot implicitly convert type 'system.collections.generic.ienumerable<consoleapplication1.program.branch>' 'consoleapplication1.program.branch'. explicit conversion exists (are missing cast?)    c:\users\dotancohen\testsavedatabase\consoleapplication1\consoleapplication1\program.cs 35  12  consoleapplication1 

however, explicitly casting so:

    branch thebranch = (branch) in branches                         let valuebranchname = i.branchname                         valuebranchname == toselect                         select i; 

returns error:

unable cast object of type 'whereselectenumerableiterator`2[<>f__anonymoustype0`2[consoleapplication1.program+branch,system.string],consoleapplication1.program+branch]' type 'branch'. 

can linq not return object, or missing obvious?

thanks.

your query returns sequence of branches (there may many branches satisfy predicate), if want first branch has name "one" (or null if there none match requirement) use:

branch thebranch = this.branches.firstordefault(b => b.branchname == "one"); 

i avoid public fields , use properties instead:

public class branch {     public int id { get; set; }     public string name { get; set; } 

Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -