代码之家  ›  专栏  ›  技术社区  ›  eugeneK

如何从列表中删除相同的项?

  •  4
  • eugeneK  · 技术社区  · 14 年前

    我有一个列表,在这个列表中,每当SQL查询以某个值运行时,我从数据库中选择用户,并在一次中选择一个用户,因此我不能限制SQL中相同的用户。

    我的列表包括:

    list[0] = "jerry"
    list[1] = "tom"
    list[2] = "jerry"
    

    我希望从列表中删除任何(第一个或最后一个不重要)。

    谢谢

    5 回复  |  直到 14 年前
        1
  •  15
  •   Doctor Blue    14 年前

    Linq可以解决这个问题:

    List<string> names = new List<string> { "Tom", "Jerry", "Tom" };
    IQueryable<string> distinctItems = names.Distinct();
    

    distinctItems.ToList();
    

    以下是 MSDN .

    edit:non-linq示例(使用来自 List class ):

    List<string> names = new List<string> { "Tom", "Jerry", "Tom" };
    List<string> distinctNames = new List<string>();
    foreach (var name in names)
    {
        if (!distinctNames.Contains(name))
        {
            distinctNames.Add(name);
        }
    }
    
        2
  •  22
  •   Lee    14 年前
    IEnumerable<string> uniqueUsers = list.Distinct();
    

    您还可以使用哈希集:

    HashSet<string> uniqueUsers = new HashSet<string>(list);
    
        3
  •  6
  •   Alex McBride    14 年前

    可以使用distinct()linq扩展名。

    var list = new List<string> { "Tom", "Jerry", "Tom" };
    
    var uniqueList = list.Distinct();
    
        4
  •  2
  •   LukeH    14 年前

    使用 Distinct 如其他答案中建议的那样,将保留原始列表的完整性,并返回单独的 IEnumerable<> 包含列表中不同项的序列。

    另一种方法是直接从原始列表中删除重复项,使用 RemoveAll :

    var temp = new HashSet<string>();
    yourList.RemoveAll(x => !temp.Add(x));
    
        5
  •  1
  •   anishMarokey FIre Panda    14 年前

    你可以使用 list.distinct();