Reputation: 31481
How does one select a specific object using query-expression style Linq?
private static ObservableCollection<Branch> _branches = new ObservableCollection<Branch>();
public static ObservableCollection<Branch> Branches
{
get { 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 = from i in Branches
let valueBranchName = i.branchName
where 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 the following error:
Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<ConsoleApplication1.Program.Branch>' to 'ConsoleApplication1.Program.Branch'. An explicit conversion exists (are you missing a cast?) C:\Users\dotancohen\testSaveDatabase\ConsoleApplication1\ConsoleApplication1\Program.cs 35 12 ConsoleApplication1
However, explicitly casting like so:
Branch theBranch = (Branch) from i in Branches
let valueBranchName = i.branchName
where valueBranchName == toSelect
select i;
Returns this error:
Unable to cast object of type 'WhereSelectEnumerableIterator`2[<>f__AnonymousType0`2[ConsoleApplication1.Program+Branch,System.String],ConsoleApplication1.Program+Branch]' to type 'Branch'.
Can Linq not return an object, or am I missing something obvious?
Thanks.
Upvotes: 0
Views: 6435
Reputation: 1547
You need to use .First() to get the first Branch item from your query.
Linq queries return collections of objects.
Upvotes: 1
Reputation: 34349
Your query returns a sequence of branches (there may be many branches that satisfy the predicate), if you want the first branch that has the name "one" (or null if there are none that match the requirement) then use:
Branch theBranch = this.Branches.FirstOrDefault(b => b.branchName == "one");
I would also avoid public fields and use properties instead:
public class Branch
{
public int Id { get; set; }
public string Name { get; set; }
Upvotes: 9