-1

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.

Community
  • 1
  • 1
3xGuy
  • 2,235
  • 2
  • 29
  • 51

4 Answers4

2
var values = Enumerable.Range(2, 1999)
                       .Select(i => ws.cells[i,3])
                       .Distinct()
                       .ToList();
nvoigt
  • 75,013
  • 26
  • 93
  • 142
0
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);
    }
}
mac
  • 485
  • 1
  • 6
  • 29
0

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);
    }
}
Brian Dishaw
  • 5,767
  • 34
  • 49
0

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.

David
  • 10,458
  • 1
  • 28
  • 40