Is there a C# IN operator?

后端 未结 14 1836
说谎
说谎 2020-12-08 03:51

In SQL, you can use the following syntax:

SELECT *
FROM MY_TABLE
WHERE VALUE_1 IN (1, 2, 3)

Is there an equivalent in C#? The IDE seems to

14条回答
  •  离开以前
    2020-12-08 04:12

    There is no in operator that looks for a value in a collection, instead it's a method of the collection, called Contains.

    The most scalable solution is to use a HashSet as the collection. Checking for a value in a HashSet is close to an O(1) operation, compared to doing it in a List where it is an O(n) operation. That means that you can pack a lot of values in a HashSet and it's still fast, while looking for a value in a List gets slower the more values you have.

    Example:

    var set = new HashSet();
    set.Add(1);
    set.Add(2);
    set.Add(3);
    
    var result = items.Select(i => set.Contains(i.value));
    

提交回复
热议问题