Search list of objects - c#

I get a list of security groups a user belongs to as array of objects. I use DirectoryEntry to get active directory properties and one of the properties is "memberOf" (de.properties["memberOf"].value). The return values is an "array of objects". Each element of this array of objects look something like:
"CN=SITE_MAINTENANCE,OU=CMS,OU=SD,OU=ESM,OU=Engineering Systems,DC=usa,DC=abc,DC=domain,DC=com"
I can loop through the elements, cast each element as "string" and search this way. I just thought there might be an easier way that does not require looping.
I need to be able to find the one(s) with OU=CMS in it.
Thanks.

Loop through the array and then use indexOf or Regexp search for the string "OU=CMS". If it exists in the string, then you've "found the one(s) with OU=CMS in it."
You can do anything like throwing the items into a new list or whatever you want.

list.Where(a=>a.ToString().Contains("OU=CMS")).ToList();

You can use like follows
string listString="CN=SITE_MAINTENANCE,OU=CMS,OU=SD,OU=ESM,"+
"OU=Engineering Systems,DC=usa,DC=abc,DC=domain,DC=com"
Using linq:
listString.Split(',').Contains("OU=CMS")
W/o linq:
Array.IndexOf(listString.Split(','), "OU=CMS") >= 0

you can search required value by foreach loop

Related

Splitting large string in c# and adding values in it to a List

I have a string as shown below
string names = "<?startname; Max?><?startname; Alex?><?startname; Rudy?>";
is there any way I can split this string and add Max , Alex and Rudy into a separate list ?
Sure, split on two strings (all that consistently comes before, and all that consistently comes after) and specify that you want Split to remove the empties:
var r = names.Split(new[]{ "<?startname; ", "?>" }, StringSplitOptions.RemoveEmptyEntries);
If you take out the RemoveEmptyEntries it will give you a more clear idea of how the splitting is working, but in essence without it you'd get your names interspersed with array entries that are empty strings because split found a delimiter (the <?...) immediately following another (the ?>) with an empty string between the delimiters
You can read the volumes of info about this form of split here - that's a direct link to netcore3.1, you can change your version in the table of contents - this variant of Split has been available since framework2.0
You did also say "add to a separate list" - didn't see any code for that so I guess you will either be happy to proceed with r here being "a separate list" (an array actually, but probably adequately equivalent and easy to convert with LINQ's ToList() if not) or if you have another list of names (that really is a List<string>) then you can thatList.AddRange(r) it
Another Idea is to use Regex
The following regex should work :
(?<=; )(.*?)(?=\s*\?>)

How To Add Items From a ComboBox to a List Collection

I've got a combo box with a few strings. I would like to add those string to a List collection. Is this the correct way of doing it?
List<string> comboItems = new List<string>();
foreach(string passItems in comboEmail.Items)
{
comboItems.Add(passItems);
}
A slightly different way:
List<string> comboItems = comboEmail.Items.Cast<string>().ToList();
That is a perfectly valid approach.
You can also cast to string and use AddRange to create a one-liner.
comboItems.AddRange(cb.comboEmail.Cast<string>());
Your approach is simple enough. Use it.
Sometimes simple foreach statement with one line code inside
will be more readable then nice looking one line LINQ code.
Anyway both versions will be doing almost same work. LINQ can be even slowly then foreach

Find a string in a list of strings in c#

I am trying to find if a list of strings contains a specific string in C#.
for example: Suppose I have 3 entries in my list
list<string> s1 = new List<string>(){
"the lazy boy went to the market in a car",
"tom",
"balloon"};
string s2 = "market";
Now I want to return true if s1 contains s2, which it does in this case.
return s1.Contains(s2);
This returns false which is not what I want. I was reading about Predicate but could not make much sense out of it for this case.
Thanks in advance.
The simplest way is to search each string individually:
bool exists = s1.Any(s => s.Contains(s2));
The List<string>.Contains() method is going to check if any whole string matches the string you ask for. You need to check each individual list element to accomplish what you want.
Note that this may be a time-consuming operation, if your list has a large number of elements in it, very long strings, and especially in the case where the string you're searching for either does not exist or is found only near the end of the list.
Contains' alternative could be IndexOf:
var res = s1.Any(s => s.IndexOf(s2, StringComparison.Ordinal) >= 0)
StringComparison.Ordinal passed as parameter because Contains() also use it internally.
Peter Duniho's answer is generally the best way. I am providing an alternate solution. This one does not require LINQ, lamdas, or loops. This only requires string built-in type's methods.
string.Concat(listOfString).Contains("data");
Note: This approach can lead to incorrect results. For example:
string.Concat("da", "ta").Contains("data");
will return true when it should be false;

Remove duplicates from list using criteria

I want to remove duplicate filenames from a list that contains:
http://www.test.com/download/imagename_A.jpg
http://www.test.com/download/imagename_B.jpg
http://www.test.com/download/imagename_C.jpg
http://fc07.test.net/fs49/f/2009/216/6/f/imagename_A.jpg
http://fc09.test.net/fs49/f/2009/195/d/8/imagename_B.jpg
I want the final list to find duplicates that have the SAME filename, where if they do, the domain.net is selected over the domain.com, resulting in this final list:
http://fc07.test.net/fs49/f/2009/216/6/f/imagename_A.jpg
http://fc09.test.net/fs49/f/2009/195/d/8/imagename_B.jpg
http://www.test.com/download/imagename_C.jpg
I suspect that this can be done with linq (I found this article - Find Duplicate in list but with criteria), but I don't know enough about linq to make it work for me.
var result = urls.GroupBy(url => Path.GetFileName(url))
.Select(g => g.OrderByDescending(u=>new Uri(u).DnsSafeHost.EndsWith(".net")).First())
.ToList();
You can use string.split('/') to split the URL (after converting URL to string) by "/" then compare the file names by checking the last position of the array that is created. Then you can split the second position of the array with string.split('.') and check for .net/.com in the third position of that array.

Check if dictionary contains substring?

Say I have two dictionaries with the following key value pairs:
1, "Hello"
2, "Example"
And another dictionary as follows:
1, "HelloWorld"
2, "Example2"
I want to find out if these dictionaries contain the substring "hello" within them. dictionary.ContainsValue("Hello") will work for the first example but not the second one. How can I check for existence of a substring in all values in a dictionary?
Just use Any to to check for the first Value that contains "Hello"
dictionary.Any(kvp=>kvp.Value.Contains("Hello"))
Dictionary doesn't allow to search for substrings. To find it, you need to enumerate all values and check each for substring, as suggested by juharr. However, this method is highly inefficient. Use it only if you don't care about search performance at all.
If you need good performance, use suffix array algorithm. https://en.wikipedia.org/wiki/Suffix_array
dictionary.Values.Any(v => v.Contains("Hello"));
Dictionary isn't an IEnumerable itself so it won't have LINQ extensions apply to it.

Categories