Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to compare the array element with number.
ArrayList arr_obj = new ArrayList();
double a=1;
arr_obj.Add(1);
arr_obj.Add(2);
for(i = 0; i < arr_obj.Count; i++)
{
if (arr_obj[i] == a)
{
Debug.Log("ext");
}
}
This code does not work. Any ideas?
Yo are comparing an object to a double which won't compile. You will either have to store doubles in the ArrayList (as below) or first cast the values to int and then to double Ie (double)(int)arr_obj[i] because you can only unbox to the exact same type as you boxed (in your case that's int)
If you wish to stick to an ArrayList, not recommended, change to
ArrayList arr_obj = new ArrayList();
double a=1.0;
arr_obj.Add(1.0);
arr_obj.Add(2.0);
for(i=0;i<arr_obj.Count;i++){
if ((double)arr_obj[i]==a) {
Debug.Log("ext");
}
}
or you could use a List<double>
var list = new List<double>{1.0,2.0};
var a=1.0;
for(i=0;i<list.Count;i++){
if (list[i]==a) {
Debug.Log("ext");
}
}
You can convert it with Convert.ToDouble(arr_obj[i])
You have to cast the ArrayList to double:
(double)arr_obj[i]
ArrayList can contain any type beacause it is a list of objects. So, if you are going to cast it like this, you need to be sure that each array list is of type double by only putting doubles in the array list, or check it before casting like:
if (arr_obj[i] is double)
{
if ((double)arr_obj[i] == a)
{
Console.WriteLine(arr_obj[i].ToString() + " is double");
}
}
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
public Array ListToArray(List<Object> list)
{
//for example i need convert list to string[] (not knowing that objects is strings)
}
I have a list of objects.
All objects of the same type.
But for me the type is not known.
The type can be for example a String, or any other class.
I need to convert this List to the array of inherited classes.
How can I do?
You can use Array.CreateInstance to create an array of the desired type at runtime and then fill it using Array.Copy, e.g.:
public Array ListToArray(List<Object> list)
{
// assume there is at least one element in list
Array arr = Array.CreateInstance(list[0].GetType(), list.Count);
Array.Copy(list.ToArray(), arr, list.Count);
return arr;
}
Now ListToArray(new List<object>{1,2}) will return an int[] and ListToArray(new List<object>{"1","2"}) will return a string[] (obviously typed as Array).
You might want this
var result = list.Cast<Object>().ToArray();
or for generic type parameter, you can use
var result = list.Cast<T>().ToArray();
If you have a Type instance (known at runtime), then you can't cast it, and there's actually no point in doing so. You'll have to use reflection.
If you have a generic type parameter T, then you can cast it like this:
public class Something<T>
{
public void ListToArray(List<Object> list)
{
var instances = list.Cast<T>().ToArray();
}
}
Or, if you want to filter the list's content and obtain those who actually are instances of type T, use this instead:
var instances = list.OfType<T>().ToArray();
For your example this should work (if it's a string)
var stringArray = list.Select(x=>x.ToString()).ToArray();
you can do other casting in select like:
var stringArray = list.Select(x=> x as yourType).ToArray();
using as you will cast object to type you want and it will return null if cast is not possible
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am making a sort of statistical software that firstly needs to 'detect' the datatype of an array.
Firstly, X[,] is an array of sometype, can be all strings, all double, all ints or a combination of all.
Now, for every column X[] I need to know the datatype. Like:
If everything is 0 or 1, then Boolean (or binomial)
elseIf everything is integer, then integer
elseIf everything is double, then double
else: String
I need something like this in C#.
So it seems what you're trying to do here is find the "lowest common denominator" of types here. The most derived type that all of the items in the collection "are".
We'll start out with this helper method to get the entire type hierarchy of an object (including itself):
public static IEnumerable<Type> BaseClassHierarchy(object obj)
{
Type current = obj.GetType();
do
{
yield return current;
current = current.BaseType;
} while (current != null);
}
Now we can take a sequence of objects, map each to its hierarchy, intersect all of those sequences with each other, and then the first item of that result is the most derived type that is common to all of the other objects:
public static Type MostDerivedCommonType(IEnumerable<object> objects)
{
return objects.Select(o => BaseClassHierarchy(o))
.Aggregate((a,b)=> a.Intersect(b))
.First();
}
One simple idea is you can try to cast/parse as the different types and if that fails, move on to the next type. A very brief example of this is:
foreach (var element in myArray) {
double parsedDouble; int parsedInt;
var defaultValue = element.ToString();
if (Double.TryParse(defaultValue, out parsedDouble)) {
// you have something that can be used as a double (the value is in "parsedDouble")
} else if (Int32.TryParse(defaultValue, out parsedInt)){
// you have something that can be used as an integer (the value is in "parsedInt")
} else {
// you have something that can be used as an string (the value is in "defaultValue")
}
}
I believe that should probably get you started. Good luck!
Note
As other's have said - it is better to use strong types in C#. In most cases you can probably select a single type and use that rather than performing the checks above.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need the fastest algorithm in .NET C# to compare two large collections (200000 records in each collection). I need to validate each row of collection 1 with each row of collection 2 and return the row of collection 1 which has duplicate records in collection 2.
Please suggest a linq query or lookup table which ever is faster..The records are like A2368FG,AD5686,B678SD,C68AGFD,...
private bool CheckValidCode(string stdCode, List<COde> CodeMap, out int count)
{
bool bRetVal = true;
count = 1;
try
{
List<COde> tempCodeMap = new List<COde>();
for (int i = 0; i < CodeMap.Count; i++)
{
if (CodeMap[i].StandardCode == (stdCode))
{
tempCodeMap .Add(customerCodeMappings[i]);
if (CodeMap[i + 1].StandardCode == (stdCode))
{
tempCodeMap .Add(CodeMap[i + 1]);
}
break;
}
}
return tempCodeMap ;
}
}
Are they simple string objects in each? If so, you can use something like
Collection1.Intersect(collection2)
Which will return all record that exist in both collections.
Is that what you wanted? It is not clear from your question if you want to find records that exist in collection1 and multiple times in collection2. If that is what you want, you will need to dig deeper.
Methods like Intersect() etc. should help.
Don't use collections, use Set<T> classes (or convert your collections to sets).
Then you can call methods like Intersect(), it is just faster (but you trade of memory for speed)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
class abc
{
public object test(params object[] par)
{
//I need Count of the parameter here which means to check par contains 1 or 1,2
}
}
I access the class like,
abc obj =new abc();
obj.test(1);
(or)
obj.test(1,2);
my question is, there is possible to send 1 or 1,2 .I need the count of the How many parameters are in the Object in test class?How to do this?
Use Array.Length property.
public object test(params object[] par)
{
var count = par == null ? 0 : par.Length;
}
You can use Length property of object array.
public object test(params object[] par)
{
int length = par == null ? 0 : par.Length;
}
You can use Length property
Try This:
int len=par.Length;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to calculate the total for a list in my C# program, I have gotten help from several people in my class and we can't seem to find the problem, my code is,
int totalB = 0;
Cards.ForEach(delegate(ConsoleApplication1.Program.CreditCard Balance)
{
totalB= totalB + Balance;
});
The error is this Error 1 Operator '+' cannot be applied to operands of type 'int' and 'ConsoleApplication1.Program.CreditCard'
Any help for this would be much appreciated as I have no idea and neither do the people that tried to help me with this issue
I'm guessing you have a class like:
partial class CreditCard
{
public int Balance {get; set;}
}
So following what you have, explicitly, you most likely intended:
int totalB = 0;
Cards.ForEach(delegate(ConsoleApplication1.Program.CreditCard card)
{
totalB = totalB + card.Balance;
});
This iterates over each item in your Cards collection, and adds the value of the Balance property to totalB. Note I have called the variable card in the delegate to further illustrate what is going on - the delegate will be called once for each item in the collection. Inside, you can pick out the Balance property and add it to totalB.
Note you can also do this in a number of other ways:
Using LINQ:
int totalB = Cards.Sum(card => card.Balance);
Using a lambda expression instead of an explicit delegate:
int totalB = 0;
Cards.Foreach(card => {totalB += card.Balance;});
Using a foreach loop:
int totalB = 0;
foreach(CreditCard card in Cards)
totalB += card.Balance;
(If you are not familiar with it, the x += y is the same as x = x + y.)
As far as getting sum of list is concerned. it is as simple as (assuming Cards is a list)
Cards.Sum(x=>x.YourPropertyToSum);
Your Error:
The error is this Error 1 Operator '+' cannot be applied to operands of type 'int' and 'ConsoleApplication1.Program.CreditCard'
you are trying to add an int with ConsoleApplication1.Program.CreditCard (what is this) which is obviously not a type that can be added to int. Hence the error you are getting.