Linq:根据属性选择对象

时间:2012-03-10 19:22:25

标签: c# linq oop

如何使用查询表达式样式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可以不归还某个物体,还是我遗漏了一些明显的东西?

感谢。

2 个答案:

答案 0 :(得分:9)

您的查询返回一系列分支(可能有许多分支满足谓词),如果您希望第一个分支的名称为“one”(如果没有匹配要求,则返回null),然后使用:

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

我也会避免使用公共字段并使用属性:

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

答案 1 :(得分:1)

您需要使用.First()从查询中获取第一个分支项目。

Linq查询返回对象集合。