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.
Related
I'm using this code to check if the string (oCode/ originalCode) exists in the array (the string is written by user):
if (dic.cs.Any(code.Contains)) //dic.cs is in another class (cs is the array), the code variable is what I look for in the array
{
//I want to get the string was found in the array with the "Contains" function
}
I want to get the string that was found in the array with the Contains() function.
If it's possible to have multiple matches, then use this:
var foundCodes = dic.cs.Where(code.Contains);
foreach(var foundCode in foundCodes)
{
}
Otherwise:
var foundCode = dic.cs.FirstOrDefault(code.Contains);
if (!String.IsNullOrEmpty(foundCode))
{
}
You need a lambda expression in the Any method:
https://code.msdn.microsoft.com/LINQ-Quantifiers-f00e7e3e#AnySimple
var answer = yourArray.any(a => a == "WhatYouAreLookingFor");
if answer is true, then you found it.
I believe what you need is the array IndexOf method. https://msdn.microsoft.com/en-us/library/system.array.indexof(v=vs.110).aspx
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);
I got question, what is the best way to transfer information from class to class. I mean, I tried with return strings, where I have 3 items in listbox and they are named e.g. Easy Normal and Hard and then strings are named as items. It didn't work well for me, because than I loaded method, he returned me the string, but I cant use this in other class. Im doing it like this, by creating first in the first class:
if(listBox1.SelectedItem.ToString() == "Easy")
{
return "Easy";
}
And then, in second class:
if(class.string1() == "Easy")
{
Do something.
}
It doesn't work. Do you guys can maybe help me? Or this question is too newbie, and I have to learn and search more.
I prefer to utilize enumerations rather than "magic strings". They are type safe and less error-proned. You can convert a string to an enum as well which lends itself well to your problem:
public enum DifficultyEnum {
NULL,
Easy,
Medium,
Hard
}
public DifficultyEnum GetDifficulty() {
var difficulty = DifficultyEnum.NULL;
var selItem = listBox1.SelectedItem.ToString();
Enum.TryParse<DifficultyEnum>(selItem, out difficulty);
return difficulty;
}
Then in your other class:
swtich (classInstance.GetDifficulty()) {
case Easy:
break;
case Medium:
break;
case Hard:
break;
case NULL: /*Hopefully you don't get here but be defensive and expect that somehow they'll manage to do so =P */
break;
}
Edit:
This is an issue of preference but you can also make the GetDifficulty() into a property instead like so:
public DifficultyEnum Difficulty {
get {
var difficulty = DifficultyEnum.NULL;
var selItem = listBox1.SelectedItem.ToString();
Enum.TryParse<DifficultyEnum>(selItem, out difficulty);
return difficulty;
}
}
You seem to be asking a few different questions here.
How you transfer information between classes depends on the type of classes you are using and the type of data you want to transfer. The simplest way to share data is probably to have a method that provides the data (either as return values, reference parameters, or a class returned that contains the data).
Beyond that, you need to be more specific about what "doesn't work" means. I can see it would work assuming it's set up correctly. However, it's not very efficient because comparing strings requires comparing each character in the string. It would make more sense to define an enum.
public enum Difficulty
{
Easy,
Normal,
Hard
}
And compare it like this:
if(classInstance.Difficulty == Difficulty.Easy)
{
// Do something.
}
Of course, your class will need to determine which list item is selected and convert it to an enum.
I need for example the number of list-items, that are NOT "".
ATM, I solve it like this:
public int getRealCount()
{
List<string> all = new List<string>(originList);
int maxall = all.Count;
try
{
for (int i = 0; i < maxall; i++)
{
all.Remove("");
}
}
catch { }
return all.Count;
}
No question, performance is pretty bad. I'm lucky it's just a 10-items-list, but on a phone you should avoid such code.
So my question is, how can I improve this code?
One idea was: there could already be a method for that. The econd method would be: that all could be filled with only the items that are not "".
How should I solve this?
Thanks
Sounds like you want:
return originList.Count(x => x != "");
There's no need to create a copy of the collection at all. Note that you'll need using System.Linq; in your using directives at the start of your source code.
(Note that you should not have empty catch blocks like that - it's a terrible idea to suppress exceptions in that way. Only catch exceptions when you either want to really handle them or when you want to rethrow them wrapped as another type. If you must ignore an exception, you should at least log it somewhere.)
If performance is your concern, then you should keep a collection that is only for these items.
If performance is not a big deal, I would suggest you use a Linq query on your collection. The cool thing about Linq is that the search is delayed until you need it.
int nonEmptyItemCount = originList.Count(str => !string.IsNullOrEmpty(str));
You could also do
int nonEmptyItemCount = originList.Count(str => str != "");
You should use LINQ. Install ReSharper, it'll generate it for you.
Also, don't create an int maxall = all.Count and then use it in your for loop.
For mobile apps you shouldn't use unnecessary memory so just use all.Count in the for loop.
You're calling all.remove("") for every item in the list all. Why not just call it once? You're not using i at all in your code...
Why not:
public int getRealCount()
{
List<string> all = new List<string>(originList);
int erased =all.RemoveAll(delegate(string s)
{
return s == "";
});
return all.Count - erased;
}
Update:
Fixed the issue I had. This is without lambda's.
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.