如果项目是唯一的,则写入列表的 LINQ 语句

LINQ statement to write to a list if item is unique

我有一个名为 'Categories' 的字符串列表和一个名为 'category' 的字符串。使用 LINQ,仅当 'category' 不存在于列表中时,我如何将 'category' 添加到 'Categories'?

您根本不需要 Linq:

if(!categories.Contains(category))
    categories.Add(category);

LINQ 用于查询数据。你不需要 LINQ。此外,如果您只对不同的项目感兴趣,请使用 HashSet<T>

HashSet<string> categories = new HashSet<string>();
categories.Add("category");

参见:HashSet<T>

A HashSet collection is not sorted and cannot contain duplicate elements. If order or element duplication is more important than performance for your application, consider using the List class together with the Sort method.

如果元素的顺序很重要,那么您可以使用 List<T> 进行检查,例如:

List<string> categories = new List<string>();
if(!categories.Contains("category"))
{  
    categories.Add("category");
}

首先,你真的需要一个列表吗? (特别是索引访问?)

如果您只需要一组可以循环访问的独特项目,您最好使用 HashSet。那么它就是:

categories.Add(category);    // return 'false' if category already present.