2012-03-10 11 views
0

クエリ式スタイルLinqを使用して特定のオブジェクトを選択するにはどうすればよいですか?このエラーLinq:プロパティに基づいてオブジェクトを選択

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のオブジェクトを返すことはできませんが、明示的にそうように、鋳造、しかし

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 

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; 
    } 
} 

は、次のエラーを返します。 、または私は何かを逃しているobviああ?

ありがとうございました。

答えて

9

名前が "1"の最初のブランチ(要件に一致するものがない場合はnull)を使用する場合は、一連のブランチが返されます(述語を満たすブランチが多数ある場合があります)。 :

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

私はまた、代わりに、公共分野と使用特性を回避する:

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

ありがとう、私はなぜそれがスローされたか理解している今、エラーメッセージは非常に明確です! – dotancohen

1

をあなたのクエリから最初のブランチアイテムを取得するには1次回()を使用する必要があります。

Linqクエリはオブジェクトのコレクションを返します。

+0

ありがとうマギー! – dotancohen

関連する問題