2012-03-10 53 views
0

一個人如何使用查詢表達式風格的LINQ選擇特定對象選擇的對象?的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; 
    } 
} 

返回以下錯誤:

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 

然而,明確鑄像這樣:

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

返回此錯誤:

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

能的LINQ不會返回一個對象,或者我錯過了什麼obvi OU中?

謝謝。

回答

9

查詢返回分支的序列(可能有很多分支滿足謂詞),如果你想擁有的名稱爲「一」(或空,如果有沒有匹配的要求是)第一個分支,然後使用:

Branch theBranch = this.Branches.FirstOrDefault(b => b.branchName == "one"); 

我也將避免公共領域和使用性能,而不是:

public class Branch 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
+0

謝謝你,現在該錯誤信息是很清楚,我明白爲什麼它被拋出! – dotancohen 2012-03-10 19:35:20

1

您需要使用。首先()從查詢得到的第一個分支項目。

LINQ查詢返回對象的集合。

+0

謝謝瑪吉! – dotancohen 2012-03-10 19:45:23