Check All Elements for String - c#

I want to check if my array class has the string "Unavailable" contained for all elements:
classApplicantNDatesCount[] applicantCounts = null;
....
...
applicantCounts = appCount.ToArray();
Specifically this "part" of the array I need to search through:
applicantCounts[i].NadraDateAvailableforApplicant = "All Requested Slots UnAvailable"
So I need to check if all of applicantCounts[i].NadraDateAvailableforApplicant elements contains the string "Unavailable".
I have looked into Array.TrueforAll but not found a way to apply it to my situtation.
Apologies I don't think Im using the correct terminology which might make this slightly unclear.....

LINQ eats this sort of thing for breakfast:
applicantCounts.All(a => a.NadraDateAvailableforApplicant.Contains("Unavailable"))
We're using .All here to check if a condition is true for all elements of an enumerable.
Note you have a capitalization typo in the string search.

Using Array.TrueForAll would look like this:
bool all = Array.TrueForAll(
applicantCounts,
x => x.NadraDateAvailableforApplicant.Contains("Unavailable")
);

As for #Benjamin's approach, i would use IndexOf instead of Contains where you can specify a StringComparison in case you'd like a case insensitive search and or specify CultureInfo:
applicantCounts.All(app => app.NadraDateAvailableforApplicant.IndexOf("Unavailable", StringComparison.OrdinalIgnoreCase) >= 0);

Related

Check if Characters in ArrayList C# exist - C# (2.0)

I was wondering if there is a way in an ArrayList that I can search to see if the record contains a certain characters, If so then grab the whole entire sentence and put in into a string. For Example:
list[0] = "C:\Test3\One_Title_Here.pdf";
list[1] = "D:\Two_Here.pdf";
list[2] = "C:\Test\Hmmm_Joke.pdf";
list[3] = "C:\Test2\Testing.pdf";
Looking for: "Hmmm_Joke.pdf"
Want to get: "C:\Test\Hmmm_Joke.pdf" and put it in the Remove()
protected void RemoveOther(ArrayList list, string Field)
{
string removeStr;
-- Put code in here to search for part of a string which is Field --
-- Grab that string here and put it into a new variable --
list.Contains();
list.Remove(removeStr);
}
Hope this makes sense. Thanks.
Loop through each string in the array list and if the string does not contain the search term then add it to new list, like this:
string searchString = "Hmmm_Joke.pdf";
ArrayList newList = new ArrayList();
foreach(string item in list)
{
if(!item.ToLower().Contains(searchString.ToLower()))
{
newList.Add(item);
}
}
Now you can work with the new list that has excluded any matches of the search string value.
Note: Made string be lowercase for comparison to avoid casing issues.
In order to remove a value from your ArrayList you'll need to loop through the values and check each one to see if it contains the desired value. Keep track of that index, or indexes if there are many.
Then after you have found all of the values you wish to remove, you can call ArrayList.RemoveAt to remove the values you want. If you are removing multiple values, start with the largest index and then process the smaller indexes, otherwise, the indexes will be off if you remove the smallest first.
This will do the job without raising an InvalidOperationException:
string searchString = "Hmmm_Joke.pdf";
foreach (string item in list.ToArray())
{
if (item.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
{
list.Remove(item);
}
}
I also made it case insensitive.
Good luck with your task.
I would rather use LINQ to solve this. Since IEnumerables are immutable, we should first get what we want removed and then, remove it.
var toDelete = Array.FindAll(list.ToArray(), s =>
s.ToString().IndexOf("Hmmm_Joke.pdf", StringComparison.OrdinalIgnoreCase) >= 0
).ToList();
toDelete.ForEach(item => list.Remove(item));
Of course, use a variable where is hardcoded.
I would also recommend read this question: Case insensitive 'Contains(string)'
It discuss the proper way to work with characters, since convert to Upper case/Lower case since it costs a lot of performance and may result in unexpected behaviours when dealing with file names like: 文書.pdf

XNA list elementAt

I'm using a List of platforms. I need to do something like platforms.get(i).X
I found something like that, it's called elementAt, but it only allows you to do platforms.elementAt(i).draw(). How do I check the variables of a specific object in the list?
You can access list elements with array index notation.
int x = platforms[i].X;
You could use a delegate for something like yourlist.Exists
if (stringlist.Exists(
delegate(String s)
{
return (s == "what you want to be found"); //this returns true if it is found.
}
))
{
//What you want to do if it is found.
}
Lookup more info about using lists and delegates and you should stumble on a way you could use this to solve your problem.

Returning the existence of a key in a dict by searching key substring

I have a dictionary of string people (key) and string addresses (value). I want to have an if statement that returns true if any key in my dictionary contains the substring 'anders'. Is there any way to do this? I have tried dict.ContainsKey("anders") but that just returns true if any key is explicitly named 'anders'. I would like it to return true even if the key is anderson or andersen. I know this is a pretty strange case but i need it for a purpose.
Thanks
You'll have to iterate over the collection and check each one. The LINQ Any method makes this fairly simple:
dict.Keys.Any(k => k.Contains("anders"))
Everyone has already pointed out the obvious (and correct) Any method, but one note: Using String.Contains as the predicate will only return true if the case of the substring is also correct. To do a case-insensitive search, use a simple Regex:
dict.Keys.Any(x => Regex.IsMatch(x, "(?i)anders"));
Or use IndexOf with the StringComparison argument (as in Case insensitive 'Contains(string)'):
dict.Keys.Any(x => x.IndexOf("anders", StringComparison.InvariantCultureIgnoreCase) >= 0);
There is no "wildcard search" for dictionary keys. In order to do this type of search, you are going to lose the O(constant) search that a dictionary gives you.
You'll have to iterate over the keys of the dictionary and look for those that contain the substring you require. Note that this will be an O(n*X) iteration, where n is the number of keys and X is the average size of your key string.
There's a nifty one-liner that will help:
bool containsKey = myDictionary.Keys.Any(x => x.Contains("mySubString"));
But it's a heavy operation.
var pair = dict.FirstOrDefault(kvp => kvp.Key.Contains("anders"));
if(dict.Keys.Any(k=>k.Contains("anders")))
{
//do stuff
}
You can iterate the keys of the dictionary and check each if it contains the string:
bool found = false;
foreach (string key in dict.Keys)
{
if (key.Contains("anders"))
{
found = true;
break;
}
}
or using LINQ:
bool found = dict.Keys.Any(key => key.Contains("anders"));

C# Array contains partial

How to find whether a string array contains some part of string?
I have array like this
String[] stringArray = new [] { "abc#gmail.com", "cde#yahoo.com", "#gmail.com" };
string str = "coure06#gmail.com"
if (stringArray.Any(x => x.Contains(str)))
{
//this if condition is never true
}
i want to run this if block when str contains a string thats completely or part of any of array's Item.
Assuming you've got LINQ available:
bool partialMatch = stringArray.Any(x => str.Contains(x));
Even without LINQ it's easy:
bool partialMatch = Array.Exists(stringArray, x => str.Contains(x));
or using C# 2:
bool partialMatch = Array.Exists(stringArray,
delegate(string x) { return str.Contains(x)); });
If you're using C# 1 then you probably have to do it the hard way :)
If you're looking for if a particular string in your array contains just "#gmail.com" instead of "abc#gmail.com" you have a couple of options.
On the input side, there are a variety of questions here on SO which will point you in the direction you need to go to validate that your input is a valid email address.
If you can only check on the back end, I'd do something like:
emailStr = "#gmail.com";
if(str.Contains(emailStr) && str.length == emailStr.length)
{
//your processing here
}
You can also use Regex matching, but I'm not nearly familiar enough with that to tell you what pattern you'd need.
If you're looking for just anything containing "#gmail.com", Jon's answer is your best bets.

Fastest way to compare two lists

I have a List (Foo) and I want to see if it's equal to another List (foo). What is the fastest way ?
From 3.5 onwards you may use a LINQ function for this:
List<string> l1 = new List<string> {"Hello", "World","How","Are","You"};
List<string> l2 = new List<string> {"Hello","World","How","Are","You"};
Console.WriteLine(l1.SequenceEqual(l2));
It also knows an overload to provide your own comparer
Here are the steps I would do:
Do an object.ReferenceEquals() if true, then return true.
Check the count, if not the same, return false.
Compare the elements one by one.
Here are some suggestions for the method:
Base the implementation on ICollection. This gives you the count, but doesn't restrict to specific collection type or contained type.
You can implement the method as an extension method to ICollection.
You will need to use the .Equals() for comparing the elements of the list.
Something like this:
public static bool CompareLists(List<int> l1, List<int> l2)
{
if (l1 == l2) return true;
if (l1.Count != l2.Count) return false;
for (int i=0; i<l1.Count; i++)
if (l1[i] != l2[i]) return false;
return true;
}
Some additional error checking (e.g. null-checks) might be required.
Something like this maybe using Match Action.
public static CompareList<T>(IList<T> obj1, IList<T> obj2, Action<T,T> match)
{
if (obj1.Count != obj2.Count) return false;
for (int i = 0; i < obj1.Count; i++)
{
if (obj2[i] != null && !match(obj1[i], obj2[i]))
return false;
}
}
Assuming you mean that you want to know if the CONTENTS are equal (not just the list's object reference.)
If you will be doing the equality check much more often than inserts then you may find it more efficient to generate a hashcode each time a value is inserted and compare hashcodes when doing the equality check. Note that you should consider if order is important or just that the lists have identical contents in any order.
Unless you are comparing very often I think this would usually be a waste.
One shortcut, that I didn't see mentioned, is that if you know how the lists were created, you may be able to join them into strings and compare directly.
For example...
In my case, I wanted to prompt the user for a list of words. I wanted to make sure that each word started with a letter, but after that, it could contain letters, numbers, or underscores. I'm particularly concerned that users will use dashes or start with numbers.
I use Regular Expressions to break it into 2 lists, and them join them back together and compare them as strings:
var testList = userInput.match(/[-|\w]+/g)
/*the above catches common errors:
using dash or starting with a numeric*/
listToUse = userInput.match(/[a-zA-Z]\w*/g)
if (listToUse.join(" ") != testList.join(" ")) {
return "the lists don't match"
Since I knew that neither list would contain spaces, and that the lists only contained simple strings, I could join them together with a space, and compare them.

Categories

Resources