C# 从linq查询强制转换文本框控件
我试图从只包含以下文本框的集合中获取C# 从linq查询强制转换文本框控件,c#,wpf,linq,collections,controls,C#,Wpf,Linq,Collections,Controls,我试图从只包含以下文本框的集合中获取TextBox控件: IEnumerable<TextBox> tbx = this.grd.Children.OfType<TextBox>(); TextBox txtBox = (TextBox)tbx.Select(x => x.Name == "tbxLink"); 但它在运行时给了我以下错误消息: Unable to cast object of type 'WhereSelectEnumerableIterato
TextBox
控件:
IEnumerable<TextBox> tbx = this.grd.Children.OfType<TextBox>();
TextBox txtBox = (TextBox)tbx.Select(x => x.Name == "tbxLink");
但它在运行时给了我以下错误消息:
Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Windows.Controls.TextBox,System.Boolean]' to type 'System.Windows.Controls.TextBox'.
我错过了什么
编辑:
更多尝试,并显示更多错误消息:
使用。其中
:
Unable to cast object of type 'WhereEnumerableIterator`1[System.Windows.Controls.TextBox]' to type 'System.Windows.Controls.TextBox'.
使用.Single
:
Sequence contains no matching element
使用。首先
:
Sequence contains no matching element
使用
FirstOrDefault
或SingleOrDefault
会使tbx变量null
在如下情况下正常使用:
IEnumerable<TextBox> textBoxes = tbx.Where(x=>x.Name == "tbxLink");
如果没有该名称的文本框,它将返回null(更准确地说是默认值(TextBox)
)
或者
tbx.Single(x => x.Name == "tbxLink");
如果不存在该名称的文本框,则引发异常
如果有多个具有相同名称的文本框,则可能需要使用
tbx.FirstOrDefault(x => x.Name == "tbxLink");
或
例如,在works中按预期运行此代码:
void Main()
{
IEnumerable<TextBox> items = new List<TextBox>{
new TextBox{ Name = "One" },
new TextBox{ Name = "Two" },
new TextBox{ Name = "Three" },
new TextBox{ Name = "Four" },
};
items.Single (i => i.Name == "One").Dump();
}
class TextBox
{
public string Name {get;set;}
}
void Main()
{
IEnumerable items=新列表{
新文本框{Name=“One”},
新文本框{Name=“Two”},
新文本框{Name=“Three”},
新文本框{Name=“Four”},
};
items.Single(i=>i.Name==“一”).Dump();
}
类文本框
{
公共字符串名称{get;set;}
}
我用WPF复制了这个,例如
private void Button_Click_1(object sender, System.Windows.RoutedEventArgs e)
{
IEnumerable<TextBox> textBoxes = grid.Children.OfType<TextBox>();
var textBox = textBoxes.Single(tb => tb.Name == "one");
Debug.WriteLine(textBox.Name);
}
private void按钮\u单击\u 1(对象发送者,System.Windows.RoutedEventArgs e)
{
IEnumerable textboxs=grid.Children.OfType();
var textBox=textboxs.Single(tb=>tb.Name==“一”);
Debug.WriteLine(textBox.Name);
}
我忘了提到我也使用了“Where”子句,但这也让我失望。有多个文本框,但名称相同。那么SingleOrDefault是否也适用于此,或者仅在有一个文本框的情况下才适用?@Yustme:如果有多个同名的文本框,为什么您希望能够分配给单个textbox
变量?那么您希望tbx.First(x=>x.name==“tbxLink”),我说“名称相同”,这意味着没有一个文本框的名称与另一个文本框的名称相同。@Yustme:不,这不是“名称相同”的意思。这就是“名字是独一无二的”的意思。名字相同的意思正好相反——他们有相同的名字。如果名称确实是唯一的,那么Single
或SingleOrDefault
应该可以工作。
void Main()
{
IEnumerable<TextBox> items = new List<TextBox>{
new TextBox{ Name = "One" },
new TextBox{ Name = "Two" },
new TextBox{ Name = "Three" },
new TextBox{ Name = "Four" },
};
items.Single (i => i.Name == "One").Dump();
}
class TextBox
{
public string Name {get;set;}
}
private void Button_Click_1(object sender, System.Windows.RoutedEventArgs e)
{
IEnumerable<TextBox> textBoxes = grid.Children.OfType<TextBox>();
var textBox = textBoxes.Single(tb => tb.Name == "one");
Debug.WriteLine(textBox.Name);
}