Yanshof
Yanshof

Reputation: 9926

How to use Linq to find the right item in ItemsControl.Items

I define some ItemsControl and added to the ItemsControl.Items a 12 RadioButtons. One of the RadioButton is Checked. And i want to find the context of the Checked RadioButton.

The code that i wrote ( and does not work well )

string str = ( from t1 in itemsControl.Items.OfType<RadioButton>()
               where t1.IsChecked == true
               select t1.Content).ToString();

What is my mistake ? How can i do it in other way ( i dont want to use for / foreach loop )

Thanks.

Upvotes: 1

Views: 425

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160852

Your result currently is an IEnumerable<object> that has one element (the content of the one checked radio button) - but you just need this one element itself, for that you can use Single():

string str = ( from t1 in itemsControl.Items.OfType<RadioButton>()
               where t1.IsChecked
               select t1.Content).Single().ToString();

Also t1.IsChecked is already boolean, no need to compare it with true.

Upvotes: 2

Related Questions