简体   繁体   中英

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.

Tryed using lambda samples from Stack Owerflow and MSDN examples, but looks i`m messing something up.

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. 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

您可以使用RemoveAll

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

No need to create the pagesExist list. Just filter out all non zero rows using a simple l inq query over the DataTable . 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" .


As a side note I would recommend looking into 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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