簡體   English   中英

最簡潔的方法將ListBox.items轉換為通用列表

[英]Most succinct way to convert ListBox.items to a generic list

我正在使用C#並以.NET Framework 3.5為目標。 我正在尋找一個小的,簡潔而有效的代碼片段來將ListBox中的所有項目復制到List<String> (通用列表 )。

目前我有類似下面的代碼:

        List<String> myOtherList =  new List<String>();
        // Populate our colCriteria with the selected columns.

        foreach (String strCol in lbMyListBox.Items)
        {
            myOtherList.Add(strCol);
        }

當然,這是有效的,但我不禁感到必須有更好的方法來使用一些較新的語言功能。 我在考慮像List.ConvertAll方法,但這僅適用於通用列表而不適用於ListBox.ObjectCollection集合。

一點LINQ應該這樣做: -

 var myOtherList = lbMyListBox.Items.Cast<String>().ToList();

當然,您可以將Cast的Type參數修改為Items屬性中存儲的任何類型。

以下將使用它(使用Linq):

List<string> list = lbMyListBox.Items.OfType<string>().ToList();

OfType調用將確保僅使用列表框項目中的項目作為字符串。

使用Cast ,如果任何項目不是字符串,您將獲得異常。

這個怎么樣:

List<string> myOtherList = (from l in lbMyListBox.Items.Cast<ListItem>() select l.Value).ToList();

關於什么:

myOtherList.AddRange(lbMyListBox.Items);

編輯根據評論和DavidGouge的回答:

myOtherList.AddRange(lbMyListBox.Items.Select(item => ((ListItem)item).Value));

你不需要更多。 您將獲得Listbox中所有值的列表

private static List<string> GetAllElements(ListBox chkList)
        {
            return chkList.Items.Cast<ListItem>().Select(x => x.Value).ToList<string>();
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM