开发者

VB.NET/C# Comparison Operator for to test for set membership - like the IN Operator for SQL

开发者 https://www.devze.com 2022-12-29 14:45 出处:网络
so in SQL you can do something like: WHERE title IN(\'title1\',\'title2\',\'title3\') to test for set membership (assuming i\'m using the right phrase here). how can I do this in VB.NET/C#.NET?

so in SQL you can do something like:

 WHERE title IN('title1','title2','title3')

to test for set membership (assuming i'm using the right phrase here). how can I do this in VB.NET/C#.NET?

Exam开发者_JS百科ple:

 IF textMyTitle.text IN ("title1","title2","title 3") THEN
 'Take Action
 End If

Obviously the IN part of that statement doesn't work...whats the logical equivalent in .NET?


Try this:

Dim titles As New List(Of String)()
titles.Add("title1")
titles.Add("title2")
titles.Add("title3")

If titles.Contains(textMyTitle.text) Then
    // Do something here
End If


There are several ways of doing this. One is to create a HashSet with the values and check if it contains the string:

Dim values As new Hashet() { "title1", "title2", "title3" }
If values.Contains(textMyTitle.Text) Then
  ...
End If

If you can create the set once and resuse for several tests, this is very efficient. Checking for a value in a HashSet is close to an O(1) operation.

(Before framework 3.5 there was no HashSet, then you can use a Dictionary<string, byte> where the byte is just a dummy value.)


The closest equivalent would be:

if((new string[] {"title1", "title2", "title3"}).Contains(textMyTitle.Text)
{
    ...
}

But keeping the list of values explicitly defined in your code would be considered a bad design. This list should be defined somewhere else in your program as a collection (or, at the very list, an IEnumerable<string>), allowing you to do:

List<string> titles = new List<string>();

// add titles to the list

...

if(titles.Contains(textMyTitle.Text))
{
    ...
}


The IList interface is your friend. Since .Net 2.0, the Array class implements the interface IList<>. So you can use the Contains function of IList:

string[] vars = new string[] {"title1", "title2", "title3"}; if (((IList)vars ).Contains(textMyTitle.text)) { //Take Action }


Depending on the type of set you have. If you are free to choose the type of set you could simply keep you set in a HastSet()

so your example would look like (in c#)

var set = new System.Collections.Generic.HashSet<string>(){"title1","title2","title 3"};
if set.Contains(textMyTitle.text)
   //Take Action

List and arrays have similar methods though they will not perform as well for large sets (they might do better for small sets though but I haven't tryed)


I'd use LINQ.

See this:

How do I use LINQ Contains(string[]) instead of Contains(string)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号