Linq: Selektieren Sie das Objekt auf der Grundlage von Eigentum

Wie macht man die Auswahl eines bestimmten Objekts mithilfe von query-expression-Stil 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;
    }
}

Gibt die folgende Fehlermeldung zurück:

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

Jedoch ausdrücklich casting so:

    Branch theBranch = (Branch) from i in Branches
                        let valueBranchName = i.branchName
                        where valueBranchName == toSelect
                        select i;

Gibt diesen Fehler zurück:

Unable to cast object of type 'WhereSelectEnumerableIterator`2[<>f__AnonymousType0`2[ConsoleApplication1.Program+Branch,System.String],ConsoleApplication1.Program+Branch]' to type 'Branch'.

Können Linq-nicht ein Objekt zurückgeben, oder übersehe ich hier etwas offensichtliches?

Dank.

InformationsquelleAutor dotancohen | 2012-03-10
Schreibe einen Kommentar