A new way to check whether an element is included in a collection(like:"a".IsIn(a collection)) #4255
-
I hope the C# language adds a new method to the type system, which is used to check whether the specified element is contained in a collection. This is different ways of expression from the existing collection' method "contains". At present, although a collection has a "contains" method to check whether it contains a specified element, the semantics of the two are quite different. If we can check it in the following ways,the relationship between subject and object can be expressed more clearly. After all, we always want to use computer language in a way that is closer to the way human think. When comparing relationships contained in, sometimes it is to compare whether the value contains or not, and sometimes to compare references. Both should be achieved.
I can't think of more details for the moment, and I hope the experts can discuss more. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
I don't know if I misunderstand you, but that's the matter of a single extension method: using System.Collections.Generic;
public static class Extensions
{
public static bool IsIn<T>(this T item, ICollection<T> collection) => collection.Contains(item);
} If the extension method is in scope, the syntax would be exactly as you mentioned: int[] myValueArray = { 5, 9, 15 };
if (3.IsIn(myValueArray)) { } And for |
Beta Was this translation helpful? Give feedback.
-
Do you think any language changes are needed here? It looks to me like this a base class library request, which are taken on dotnet/runtime |
Beta Was this translation helpful? Give feedback.
-
I'm always careful with words like this. The way of human think varies for such simple expressions, and can be influenced by their mother language. Although I have the same language with you, I don't think there is a significant difference for the order. An important part of C# design philosophy should be the inference experience of IDE. Here the collection variable is typed first, so the inference of "contain" is more natural. "Contain" is a common operation for collections, but it's not that common for all objects in total. |
Beta Was this translation helpful? Give feedback.
I don't know if I misunderstand you, but that's the matter of a single extension method:
If the extension method is in scope, the syntax would be exactly as you mentioned:
And for
IsInAsValued
I don't think there is a general answer to how to implement that, so I suppose it would be necessary for you to write it yourself anyway to fulfill your own needs.