简体   繁体   English

如何将项目从组合框添加到列表集合

[英]How To Add Items From a ComboBox to a List Collection

I've got a combo box with a few strings. 我有一个带几根弦的组合框。 I would like to add those string to a List collection. 我想将这些字符串添加到列表集合。 Is this the correct way of doing it? 这是正确的做法吗?

List<string> comboItems = new List<string>();

foreach(string passItems in comboEmail.Items)
{
    comboItems.Add(passItems);
}

略有不同的方式:

List<string> comboItems = comboEmail.Items.Cast<string>().ToList();

That is a perfectly valid approach. 这是一种完全有效的方法。

You can also cast to string and use AddRange to create a one-liner. 您还可以转换为字符串,并使用AddRange创建AddRange

comboItems.AddRange(cb.comboEmail.Cast<string>());

Your approach is simple enough. 您的方法很简单。 Use it. 用它。

Sometimes simple foreach statement with one line code inside 有时内部有一行代码的简单foreach语句
will be more readable then nice looking one line LINQ code. 这样一来,它们的可读性就会更好,然后看起来只有一行LINQ代码。

Anyway both versions will be doing almost same work. 无论如何,两个版本都将完成几乎相同的工作。 LINQ can be even slowly then foreach LINQ甚至可以慢于foreach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM