Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Linq:基于属性选择对象_C#_Linq_Oop - Fatal编程技术网

C# Linq:基于属性选择对象

C# Linq:基于属性选择对象,c#,linq,oop,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)

如何使用查询表达式样式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;
    }
}
返回此错误:

Unable to cast object of type 'WhereSelectEnumerableIterator`2[<>f__AnonymousType0`2[ConsoleApplication1.Program+Branch,System.String],ConsoleApplication1.Program+Branch]' to type 'Branch'.
无法将类型为“WhereSelectEnumerableIterator`2[f_uAnonymousType0`2[ConsoleApplication1.Program+Branch,System.String],ConsoleApplication1.Program+Branch]”的对象强制转换为类型“Branch”。
Linq是否可以不返回对象,或者我是否遗漏了一些明显的内容


谢谢。

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

Branch theBranch = this.Branches.FirstOrDefault(b => b.branchName == "one");
我也会避免使用公共字段,而是使用属性:

public class Branch
{
    public int Id { get; set; }
    public string Name { get; set; }
您需要使用.First()从查询中获取第一个分支项


Linq查询返回对象的集合。

谢谢,现在我已经理解了抛出它的原因,错误消息非常清楚了!
Branch theBranch = this.Branches.FirstOrDefault(b => b.branchName == "one");
public class Branch
{
    public int Id { get; set; }
    public string Name { get; set; }