Returning an array of multiple arrays - c#

I don't really know if this is the correct method, but I wanna return an array of arrays in order to call the element of it in another function later.
static Values RetrieveXML(string XMLFile)
{
using var reader = XmlReader.Create(XMLFile);
reader.ReadToFollowing("ticket");
reader.ReadToFollowing("lignes");
string nombre = reader.GetAttribute("nombre");
int ligne = int.Parse(nombre);
Values[] _Values = new Values[ligne];
for(int i=0; i<ligne; i++){
_Values[i] = new Values();
reader.ReadToFollowing("article");
_Values[i].code = reader.GetAttribute("code");
_Values[i].qty = reader.GetAttribute("quantite");
_Values[i].net_price = reader.GetAttribute("net");
_Values[i].net_ht_price = reader.GetAttribute("net_ht");
_Values[i].tva = reader.GetAttribute("taxes");
_Values[i].num = reader.GetAttribute("numero");
_Values[i].valeur = reader.GetAttribute("base_ht");
_Values[i].remise = reader.GetAttribute("valeur_remise");
reader.ReadToFollowing("libelle");
_Values[i].libelle = reader.ReadElementContentAsString();
Console.WriteLine("-----------Using XMLToOrderLine--------------");
Console.WriteLine(_Values[i].code);
Console.WriteLine(_Values[i].valeur);
}
return _Values[];
}
public class Values
{
public string code;
public string qty;
public string remise;
public string valeur;
public string tva;
public string libelle;
public string num;
public string net_ht_price;
public string net_price;
}
And then after that I wanna call by example: Values[1].code in another function, how can I do that?

change your code like this:
static Values[] RetrieveXML(string XMLFile)
{
using var reader = XmlReader.Create(XMLFile);
reader.ReadToFollowing("ticket");
reader.ReadToFollowing("lignes");
string nombre = reader.GetAttribute("nombre");
int ligne = int.Parse(nombre);
Values[] _Values = new Values[ligne];
for(int i=0; i<ligne; i++){
_Values[i] = new Values();
reader.ReadToFollowing("article");
_Values[i].code = reader.GetAttribute("code");
_Values[i].qty = reader.GetAttribute("quantite");
_Values[i].net_price = reader.GetAttribute("net");
_Values[i].net_ht_price = reader.GetAttribute("net_ht");
_Values[i].tva = reader.GetAttribute("taxes");
_Values[i].num = reader.GetAttribute("numero");
_Values[i].valeur = reader.GetAttribute("base_ht");
_Values[i].remise = reader.GetAttribute("valeur_remise");
reader.ReadToFollowing("libelle");
_Values[i].libelle = reader.ReadElementContentAsString();
Console.WriteLine("-----------Using XMLToOrderLine--------------");
Console.WriteLine(_Values[i].code);
Console.WriteLine(_Values[i].valeur);
}
return _Values;
}
just try it.

Related

Unable to add new object to List past index 0

I'm noticing that I am unable to add to a list of objects past index 0. Any other index returns a null reference.
public class MultiValidation
{
public List<SingleValidation> validations { get; set; }
public MultiValidation(List<string> numArray)
{
for(int i = 0; i<numArray.Count; i++)
{
SingleValidation individual = new SingleValidation(Validate.idArray[i], Validate.actionArray[i], Validate.expiryArray[i]);
validations = new List<SingleValidation>();
validations.Add(individual);
Console.WriteLine(validations[i].action);
}
}
Here is the constructor used for SingleValidation
public SingleValidation(string ide, string ac, string exDate)
{
this.action = ac;
this.expiry = exDate;
this.id = ide;
}
I have tested that idArray[i],actionArray[i],expiryArray[i] are all strings.
validations = new List<SingleValidation>();
This should be outside the for loop.
{
validations = new List<SingleValidation>();
for(int i = 0; i<numArray.Count; i++)
{
SingleValidation individual = new SingleValidation(Validate.idArray[i],
Validate.actionArray[i], Validate.expiryArray[i]);
validations.Add(individual);
Console.WriteLine(validations[i].action);
}
}

Cannot implicitly convert type void to string

class Program
{
static void Main(string[] args)
{
List<string> itemsNames = new List<string>();
List<decimal> itemsPrices = new List<decimal>();
itemsNames.Add("Bread");
itemsNames.Add("Milk");
itemsNames.Add("Juice");
itemsNames.Add("Chocolate");
itemsNames.Add("Cheese");
itemsNames.Add("Ham");
itemsNames.Add("Chicken");
itemsPrices.Add(2.50M);
itemsPrices.Add(3.00M);
itemsPrices.Add(4.50M);
itemsPrices.Add(1.50M);
itemsPrices.Add(2.50M);
itemsPrices.Add(3.50M);
itemsPrices.Add(13.50M);
string result = CombineTheLists(itemsNames, itemsPrices);
Console.WriteLine("\r\nPress enter to continue...");
Console.ReadKey();
}
public static void CombineTheLists(List<string> itemNames, List<decimal> itemPrices)
{
for (int i = 0; i < itemNames.Count; i++)
{
string result = "";
string names = itemNames[i];
decimal prices = itemPrices[i];
Console.WriteLine($"The {names} costs ${prices}");
}
}
I've been trying to figure the proper way to make the function call to the method I created in the code provided. When I attempt to make the function call it just shows the cannot convert void to string error and I know it's because the method I created is and must be void. Is there a work around my issue?
If you want your function to return something, it should not be void. If you don't want it to return something, string result = is not necessary. You have to decide what you really need. (EDIT: Looks like you already did, and other answers covered this very well). Also instead of holding those two lists, you should create a class or struct to your items:
public class Item
{
public string Name { get; set; }
public decimal Price{ get; set; }
public Item(string name, decimal price)
{
Name = name;
Price = price;
}
}
And use it like this:
static void Main(string[] args)
{
List<Item> items = new List<Item>();
items.Add(new Item("Bread", 2.50M));
items.Add(new Item("Milk", 3.00M));
items.Add(new Item("Juice", 4.50M));
items.Add(new Item("Chocolate", 1.50M));
items.Add(new Item("Cheese", 2.50M));
items.Add(new Item("Ham", 3.50M));
items.Add(new Item("Chicken", 13.50M));
string result = PrintList(itemsNames, itemsPrices);
Console.WriteLine("\r\nPress enter to continue...");
Console.ReadKey();
}
public static string PrintList(List<Item> items)
{
var stringBuilder = new StringBuilder();
for (int i = 0; i < items.Count; i++)
{
string names = items[i].Name;
decimal prices = items[i].Price;
sb.AppendLine($"The {names} costs ${prices}");
}
return sb.ToString();
}
This will make your life much easier.
EDIT2: Other ways to loop through the list:
foreach:
foreach(Item i in items)
{
string name = i.Name;
decimal price = i.Price;
}
while:
int i = 0;
while(i < items.Count)
{
string name = items[i].Name;
decimal price = items[i].Price;
i++;
}
CombineTheLists does not return anything, but you're trying to assign it to a string:
string result = CombineTheLists(itemsNames, itemsPrices);
Change it to return a string (and, obviously return it, instead of using Console.WriteLine) or dont try to capture the return if you did want to just write to the console.
CombineTheLists(itemsNames, itemsPrices);
As an alternative if you were tryingg to build a string inside the method, and return it you could use a StringBuilder:
public static string CombineTheLists(List<string> itemNames, List<decimal> itemPrices)
{
var sb = new StringBuidler();
for (int i = 0; i < itemNames.Count; i++)
{
string result = "";
string names = itemNames[i];
decimal prices = itemPrices[i];
sb.AppendLine($"The {names} costs ${prices}");
}
return sb.ToString();
}
Note that I changed the return type to string - you can then call it as your original code
string result = CombineTheLists(itemsNames, itemsPrices);
Console.WriteLine(result);
Change the return type of your function
public static string CombineTheLists(List<string> itemNames, List<decimal> itemPrices)
{
for (int i = 0; i < itemNames.Count; i++)
{
string result = "";
string names = itemNames[i];
decimal prices = itemPrices[i];
Console.WriteLine($"The {names} costs ${prices}");
}
return "somestring from CombineTheLists function";
}
or
Don't expect from the function it will return string and make a simple call to the function.
When you call it with this line:
string result = CombineTheLists(itemsNames, itemsPrices);
you are taking the result of the CombineTheLists method and trying to convert its result to a string, storing the result in a variable called result.
You are not actually using the result variable, so you needn't create it in the first place.
More importantly, the return type of CombineTheLists is explicitly void:
public static void CombineTheLists(List<string> itemNames, List<decimal> itemPrices)
and as the method does not include a return statement, it does not return a string either.
To fix this you simply need to do this instead:
static void Main(string[] args)
{
List<string> itemsNames = new List<string>();
List<decimal> itemsPrices = new List<decimal>();
itemsNames.Add("Bread");
itemsNames.Add("Milk");
itemsNames.Add("Juice");
itemsNames.Add("Chocolate");
itemsNames.Add("Cheese");
itemsNames.Add("Ham");
itemsNames.Add("Chicken");
itemsPrices.Add(2.50M);
itemsPrices.Add(3.00M);
itemsPrices.Add(4.50M);
itemsPrices.Add(1.50M);
itemsPrices.Add(2.50M);
itemsPrices.Add(3.50M);
itemsPrices.Add(13.50M);
string result = CombineTheLists(itemsNames, itemsPrices);
Console.Write(result);
Console.WriteLine("\r\nPress enter to continue...");
Console.ReadKey();
}
public static string CombineTheLists(List<string> itemNames, List<decimal> itemPrices)
{
var stringBuilder = new StringBuilder();
for (int i = 0; i < itemNames.Count; i++)
{
string names = itemNames[i];
decimal prices = itemPrices[i];
stringBuilder.AppendLine($"The {names} costs ${prices}");
}
return stringBuilder.ToString();
}

xamarin forms cannot implicitly convert type 'system.threading.tasks.task<System.collections.generic list to system.collections.generic List

Hi I am new to programming, but currently I encounter xamarin forms cannot implicitly convert type 'system.threading.tasks.task> to system.collections.generic.List
as I am trying to use global variable upon launching the app to optimized the app
when I am trying to set the List of menu items into the global variable which will be access by the other pages, it gave me that error. I have no idea how to solve that issue so someone please help me
Here is my
App.cs
private static int globalVariable = 1;
public static List<MenuItemModel> foodList = new List<MenuItemModel>();
private static List<MenuItemModel> beverageList = new List<MenuItemModel>();
public static int GlobalVariable
{
get { return globalVariable; }
set { globalVariable = value; }
}
public static List<MenuItemModel> FoodList
{
get { return foodList; }
set { foodList = value; }
}
public static List<MenuItemModel> BeverageList
{
get { return beverageList; }
set { beverageList = value; }
}
public App()
{
GlobalVariable = 10;
BeverageList = getBeverageList();
FoodList = getFoodList();
}
public async Task<List<MenuItemModel>> getBeverageList()
{
ConstantCS constant = new ConstantCS();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://172.20.129.44/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = new HttpResponseMessage();
response = client.GetAsync("WebServices/menu.svc/GetBeveragesJSON").Result;
if (response.IsSuccessStatusCode)
{
string jsonString = await response.Content.ReadAsStringAsync();
dynamic dynamicObject = JsonConvert.DeserializeObject(jsonString);
int itemId_;
string itemName_;
string itemCategory_;
string itemSubCategory_;
string itemDescription_;
string itemImage_;
int itemQuantity_;
double itemPrice_;
string itemStatus_;
string itemAddOn_;
for (int i = 0; i < dynamicObject.d.Count; i++)
{
itemId_ = dynamicObject.d[i]["itemID"];
itemName_ = dynamicObject.d[i]["itemName"].ToString();
itemCategory_ = dynamicObject.d[i]["itemCategory"].ToString();
itemSubCategory_ = dynamicObject.d[i]["itemSubCategory"].ToString();
itemDescription_ = dynamicObject.d[i]["itemDesc"].ToString();
itemImage_ = dynamicObject.d[i]["itemImg"].ToString();
itemQuantity_ = int.Parse(dynamicObject.d[i]["itemQty"].ToString());
itemPrice_ = double.Parse(dynamicObject.d[i]["itemPrice"].ToString());
itemStatus_ = dynamicObject.d[i]["itemStatus"].ToString();
itemAddOn_ = dynamicObject.d[i]["itemRequest"].ToString();
string itemURL_ = constant.PhotoBaseURL + itemImage_;
beverageList.Add(new MenuItemModel(itemId_, itemName_, itemCategory_, itemSubCategory_, itemDescription_, itemURL_, itemQuantity_, itemPrice_, itemStatus_, itemAddOn_));
}
}
else
{
//Debug.WriteLine("It entered else not if");
}
return beverageList;
}
Thanks!
You're not doing anything async in getBeverageList(), so you can safely change its signature to
public List<MenuItemModel> getBeverageList()
After that, you should stop for a few days, and learn about async/await and TPL...

Assignment to struct array inside method does not work in C#?

Here is the code snippet from my LinqPad:
public class Elephant{
public int Size;
public Elephant()
{
Size = 1;
}
}
public struct Ant{
public int Size;
}
private T[] Transform2AnotherType<T>(Elephant[] elephantList)
where T:new()
{
dynamic tArray = new T[elephantList.Length];
for (int i = 0; i < elephantList.Length; i++)
{
tArray[i] = new T();
tArray[i].Size = 100;
//tArray[i].Dump();
}
return tArray;
}
void Main()
{
var elephantList = new Elephant[2];
var elephant1 = new Elephant();
var elephant2 = new Elephant();
elephantList[0] = elephant1;
elephantList[1] = elephant2;
elephantList.Dump();
var r = Transform2AnotherType<Ant>(elephantList);
r.Dump();
}
I want to change one object array of known type,Elephant,to another object array of type T. T is not a class,but limited to struct which
provided by the already existed API.And every instance of type T shares some common property,says Size,but also has their own particular property which
I have omitted in my example code.So I put dynamic keyword inside the Transform2AnotherType<T>.
And I could not even to use Dump to make sure if the assignment has made effect,thus will throw RuntimeBinderException.
My question is: how to correctly make the assignment in such a struct array and return it back properly?
I suggest change your code like this:
public class Elephant
{
public Elephant()
{
Size = 1;
}
public int Size { get; set; }
}
public struct Ant
{
public int Size { get; set; }
}
private static T[] Transform2AnotherType<T>(Elephant[] elephantList)
where T : new()
{
T[] tArray = new T[elephantList.Length];
for (int i = 0; i < elephantList.Length; i++)
{
dynamic arrayElement = new T();
arrayElement.Size = 100;
tArray[i] = arrayElement;
//tArray[i].Dump();
}
return tArray;
}
static void Main()
{
var elephantList = new Elephant[2];
var elephant1 = new Elephant();
var elephant2 = new Elephant();
elephantList[0] = elephant1;
elephantList[1] = elephant2;
//elephantList.Dump();
var r = Transform2AnotherType<Ant>(elephantList);
//r.Dump();
}

I want to retrieve data from an ArrayList using c#

I want to retrieve object data from an ArrayList;
public class Form1
{
ArrayList list = new ArrayList();
private void OnSockMessage(object sender, SockEventArgs e)
{
Regex MyRegex = new Regex("^[<][A-Za-z]");
if (e.SockMsg != null)
{
string y = e.SockMsg.ToString();
if (MyRegex.IsMatch(y) == true)
{
rrr = y;
string ipdd = SocClient[e.SocketRef].Soc.RemoteEndPoint.ToString();
//serverkey seckey;
list.Add(new serverkey(ipdd,rrr));
}
else
{
string curipadd = SocClient[e.SocketRef].Soc.RemoteEndPoint.ToString();
for (int i = 0; i < list.Count-1; i++)
{
//serverkey pk = list[i] as serverkey;
//string jj = list[i].ToString();
// serverkey pk = new serverkey(list[i].ToString());
/*********************************************
here i want to retrieve data from array list
*********************************************/
string ipadd;
if (curipadd == ipadd )
{
y = DecryptString(e.SockMsg, rrr);
listBox1.Items.Add(txtIP.Text + " <<" + y);
}
}
}
}
public class serverkey : Form1
{
string ipaddress;
string secertkey;
public serverkey(string IPAdd, string Seckey)
{
ipaddress = IPAdd;
secertkey = Seckey;
}
public string ip
{
get { return ipaddress; }
}
public string key
{
get { return secertkey; }
}
You'd be better off using a strongly typed generic List<serverkey> and a foreach loop rather than a for loop. It'll be something like
List<serverkey> list = new List<serverkey>();
//add your items as you already are
foreach(var item in list)
{
item.ip ...// use item as a serverkey
}
Having said that, if you can you use a generic for some reason, use an 'as'
ArrayList list = new ArrayList();
//add your items as you already are
foreach(var item in list)
{
var sk = item as serverkey;
sk.ip ...// use item as a serverkey
}

Categories

Resources