简体   繁体   中英

Distinct items in List

I have an excel spreadsheet that I am trying to populate a list with only unique values. I have found LinqToExcel which I would prefer not to use. At most there will be 2000 rows which isn't very much.

My thought was:

List<string> lst = new List<string>();
string item;

for (i=2; i<2001; i++)
{
    item = ws.cells[i,3];
    if(lst.**notInList**(item))
    {
        lst.Add(item);
    }
}

I know that there isn't notInList() , but I was hoping for something similar or another idea.

var values = Enumerable.Range(2, 1999)
                       .Select(i => ws.cells[i,3])
                       .Distinct()
                       .ToList();
List<string> lst = new List<string>();
string item;

for (i=2; i<2001; i++)
{
    item = ws.cells[i,3];
    if(!lst.Contains(item))
    {
        lst.Add(item);
    }
}

Use Contains instead

List<string> lst = new List<string>();
string item;

for (i=2; i<2001; i++)
{
    item = ws.cells[i,3];
    if(!lst.Contains(item))
    {
        lst.Add(item);
    }
}

If you want the items filtered for identical entries, you could use the .Distinct method from linq.

var distinctList = lst.Distinct();

There's also List.Contains(item)

If you know from the get-go that this collection should contain only unique elements, also consider using a HashSet<T> instead.

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