简体   繁体   English

列表中的不同项目

[英]Distinct items in List

I have an excel spreadsheet that I am trying to populate a list with only unique values. 我有一个Excel电子表格,我试图用唯一值填充列表。 I have found LinqToExcel which I would prefer not to use. 我找到了我不希望使用的LinqToExcel At most there will be 2000 rows which isn't very much. 最多会有2000行,不是很多。

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. 我知道这里没有notInList() ,但是我希望有类似的想法或其他想法。

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. 如果希望为相同的条目过滤项目,则可以使用linq中的.Distinct方法。

var distinctList = lst.Distinct();

There's also List.Contains(item) 还有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. 如果从一开始就知道此集合应仅包含唯一元素,则也可以考虑使用HashSet<T>代替。

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

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