简体   繁体   English

如何从列表中删除零个元素 <string> ?

[英]How to remove zero elements from List<string>?

Read couple of examples, but seems i`m doing something wrong. 阅读一些示例,但似乎我做错了什么。 Need to remove all "0" strings from a HUGE List without using hashtables. 需要从巨型列表中删除所有“ 0”字符串,而不使用哈希表。

Tryed using lambda samples from Stack Owerflow and MSDN examples, but looks i`m messing something up. 尝试使用Stack Owerflow和MSDN示例中的lambda示例,但是看起来有些混乱。

DataTable book = SQL.SqlGetTable(BookList.SelectedItem.ToString());
List<string> pagesExist = new List<string>();
for (int i = 0; i < book.Rows.Count; i++)
{
    pagesExist.Add(book.Rows[i][0].ToString());
}

var found = pagesExist.Find(x => x == "0");
if (found != null) 
    pagesExist.Remove(found);

I have a pagesExist list of 4000 string elements. 我有一个4000个字符串元素的pagesExist列表。 Supposed that 假设

var found = pagesExist.Find(x => x == "0"); 

will accumulate all zeroes in list and will remove them next string. 将累积列表中的所有零,并将其删除下一个字符串。 But somehow found results in 0 elements 但是不知何故找到了0个元素的结果

您可以使用RemoveAll

pagesExist.RemoveAll(p => p == "0");

No need to create the pagesExist list. 无需创建pagesExist列表。 Just filter out all non zero rows using a simple l inq query over the DataTable . 只需DataTable使用简单的inq查询过滤掉所有非零行。 This way your entire code is reduced to only: 这样,您的整个代码将减少为:

DataTable book = SQL.SqlGetTable(BookList.SelectedItem.ToString());
var result = book.AsEnumerable().Where(r => r.Field<int>("FieldName") != 0);

I am assuming that the column contains integers only. 我假设该列仅包含整数。 If not then keep the use Field<string> and filter for != "0" . 如果不是,则继续使用Field<string>并过滤!= "0"


As a side note I would recommend looking into SqlGetTable . 作为附带说明,我建议您查看SqlGetTable If it returns a DataTable it already brings all this data into memory from database, something that can be avoided with using linq directly over the DBMS using tools like linq-2-sql or linq-2-entities 如果它返回一个DataTable它已经将所有这些数据从数据库中带到内存中,可以通过使用linq-2-sql或linq-2-entities之类的工具直接在DBMS上使用linq来避免这种情况

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

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