Reputation: 21
score#UPDATED# This probably sounds pretty dumb but I've been stuck on this problem for three days now! I am new to C#.
I am trying to consume a web service in C#. I managed to consume the web service in Java with the following lines of code:
List x = new ArrayList<Score>();
x = topScores();
System.out.println("x" + x.size());
System.out.println("TOP SCORES:");
for (Object o : x) {
Score s1 = (Score) o;
System.out.println(s1.getScore());
}
I need to display a list of scores but can't seem to figure it out in C#. Here is where I am stuck in C#:
List<object[]> list = new List<score[]>();
I have tried loads of different variations of declaring collections but can't get past this. I think I know how to iterate through a list but I can't get past declaring it. Here is my error message:
Cannot implicitly convert type `System.Collections.Generic.List<score>' to `System.Collections.Generic.List<object>'
If I change the declaration to :
List<score> list = new List<score>();
list = service.TopScores();
I get the same error but this time I get a message saying:
"Object[] TopScores()"
What is the C# equivalent of my Java snippet? I'd really appreciate any help or suggestions! Thank you for your time!
Upvotes: 0
Views: 912
Reputation: 1600
The List<> class is in a category of collections called Generics, which allows you to create an array of strongly-typed objects. . The List part implies an array, so you don't need to declare the type as an array as well. Instead of List<object[]>
, you should just do List<object>
. You also can't change the data type of the list. If you want to create a list of Score
you should just do.
List<Score> scores = new List<Score>();
then you could populate the list with scores like
Score newScore = new Score();
scores.Add(newScore);
or whatever
Upvotes: 2
Reputation: 21
Thank you for your help...I figured it out...
LoginService service = new LoginService();
List<score> listA = new List<score>();
object[] array = listA.ToArray();
array = service.TopScores();
Upvotes: 1
Reputation: 149030
It looks like you don't need to create a List<object>
because your code always knows that the elements of the list are of type Score
. You can do this instead
List<Score> list = new List<Score>(); // Not really necessary because you assign it a different value in the next line.
list = topScores().Select(o => o.ToString()).ToList();
...
System.Console.WriteLine("x{0}", list.Length);
System.Console.WriteLine("TOP SCORES:");
foreach (var score in list) {
System.Console.WriteLine(score.GetScore());
}
However if you really want to create a List<object>
from a List<string>
the easiest way to do that is this:
List<string> stringList = ...
List<object> objectList = stringList.ToList<object>();
Upvotes: 0
Reputation: 315
You need to have the same type when declaring this list.
List<score> list = new List<score>();
then
foreach(Score score in list)
{
//do something
}
Upvotes: 0