C# Linq:基于属性选择对象
如何使用查询表达式样式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)
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; }