C# 如何将 CheckedListBox Selected Items 放入 List<X>...?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13945888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the CheckedListBox Selected Items into List<X>...?
提问by Ravishankar N
I am having a List of type X. X is a Property Level Class. Now on an event i need the CheckedListBox Selected Items into another List.
我有一个 X 类型的列表。X 是一个属性级别类。现在在一个事件中,我需要 CheckedListBox Selected Items 到另一个列表中。
How to get the output...?? The code i tried is given below...
如何获得输出......?我试过的代码如下...
public void Initialize(List<X> x1)
{
chkList.DataSource = x1;
chkList.DisplayMember = "MeterName"; // MeterName is a property in Class X
chkList.ValueMember = "PortNum"; // PortNum is a property in Class X
}
private void Click_Event(object sender, EventArgs e)
{
List<X> x2 = new List<X>();
// Here I want to get the checkedListBox selected items in x2;
// How to get it...???
}
回答by COLD TOLD
you can try the following
您可以尝试以下操作
List<X> x2 = chkList.CheckedItems.OfType<X>().ToList();
or cast as object
或投射为对象
List<object> x2 = chkList.CheckedItems.OfType<object>().ToList();
回答by Ravishankar N
i got the answer
我得到了答案
private void Click_Event(object sender, EventArgs e)
{
List<X> x2 = new List<X>();
foreach (X item in chkList.CheckedItems)
{
x2.Add(item);
}
}
回答by Joe Sisk
Here is a way that works for me:
这是一种对我有用的方法:
List<X> x2 = new List<X>();
x2 = chkList.CheckedItems.Cast<X>().ToList();
回答by Broken_Window
string[] miList = chkList.CheckedItems.OfType<object>().Select(li => li.ToString()).ToArray();
回答by Roi Snir
This is another Option
这是另一个选项
List<X> lst = new List<X>(chkList.CheckedItems.Cast<X>());