I am trying to select all data that is stored in a list where the username == the parameter. I'm having trouble printing it in the right format. Currently, the output is productsClass.Products where I'd like it to be the data. Any help or hints are greatly appreciated.
Thanks
public class Products {
public string productName;
public string productType;
public int productCost;
public string userName;
}
public class ProductController {
public List<Products> productsList;
public ProductController() {
productsList = new List<Products>();
}
public void CreateNewProduct(string username, string productName, string productType, int productCost) {
Products product = new Products();
product.userName = username;
product.productName = productName;
product.productType = productType;
product.productCost = productCost;
productsList.Add(product);
}
public void ListAllProducts(string username) {
IEnumerable<Products> listProducts = from s in productsList
where s.userName == username
select s;
foreach (var product in listProducts) {
Console.WriteLine(product);
}
}
}
CodePudding user response:
According to Object.ToString Method
Object.ToString
method return the fully qualified name of the object's type.
If you need to print product
, you have to override .ToString()
as below:
public class Products
{
...
public override string ToString()
{
return String.Format("Name: {0}, Type: {1}, Cost: {2}, UserName: {3}", productName, productType, productCost, userName);
}
}
CodePudding user response:
Your Question is a bit unclear about what exactly you want to print and in what format but given that you said you want all the data this could be a solution:
public void ListAllProducts(string username) {
IEnumerable<Products> listProducts = from s in productsList
where s.userName == username
select s;
foreach (var product in listProducts) {
Console.WriteLine(product.userName "\t" product.productName "\t" product.productType "\t" product.productCost);
}
}
This would print out all of your variables of the object. Because if you give the object as only Parameter to WriteLine() it will only print out its type.
CodePudding user response:
You cannot just print the class instance. Try to print the properties instead.
Console.WriteLine(product.productName);
CodePudding user response:
You can achieve the expect result by using System.Text.Json
then do Console.WriteLine(JsonSerializer.Serialize(product))
CodePudding user response:
If you want to show the data in a specific way the best would be to override the ToString() method in your Products class and then call it inside Console.WriteLine