c# bindingsource and linq
I have a bindingsource which has been filled out by
tableadapter.fill(DS, param1);
lets say that this bindingsource has :
char num
A 1
B 开发者_如何学编程 2
C 3
how do I get num value with given char 'A' using linq?
I could literate using foreach (DataRowView data in this.p_EM_Select_Event_TypeBindingSource) but I would like to know how to do this in linq
Thanks,
This should help:
http://msdn.microsoft.com/en-us/library/bb399401.aspx
cheers
First, you need to specify what your data type is.
Since you did not, I will create one here as a placeholder:
public class Data1
{
public Data1()
{
Character = String.Empty;
Number = -1;
Other = null;
}
public String Character { get; set; }
public int Number { get; set; }
public object Other { get; set; }
}
Now that you have a data type, we can assume that your BindingSource is populated with this type of data:
Somewhere in your code, you have to fill your BindingList:
p_EM_Select_Event_TypeBindingSource.DataSource = new List<Data1>();
Methods like below make nice wrappers for these types of tasks:
public int GetIndex(String value)
{
var result = -1;
if (!String.IsNullOrEmpty(value))
{
var list = (IList<Data1>)p_EM_Select_Event_TypeBindingSource.List;
if (list.Any(x => x.Character == value))
{
result = list.IndexOf(list.First(x => x.Character == value));
}
}
return result;
}
public int GetNumber(String value)
{
var result = -1;
if (!String.IsNullOrEmpty(value))
{
var item = list.IndexOf(list.FirstOrDefault(x => x.Character == value));
if (item != null)
{
result = item.Number;
}
}
return result;
}
To set the BindingSource to your data item with given Character "A", you can call your method:
p_EM_Select_Event_TypeBindingSource.Position = GetIndex("A");
Or, to get the Number to your data item with the given Character, you can call the similar method:
var number = GetNumber("A");
精彩评论