-2

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);
        }
    }
}
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Cale Lewis
  • 31
  • 1
  • 6
  • What's the question? You already have your query and I assume it runs. `trouble printing it in the right format.` has nothing to do with LINQ and lists. `I'd like it to be the data.` what does that mean? What do you want to display? .NET can't guess that which is why it prints the type name – Panagiotis Kanavos Oct 22 '21 at 07:39
  • change `Console.WriteLine(product);` to `Console.WriteLine(product.productName);` – Tatranskymedved Oct 22 '21 at 07:41
  • 1
    Alternative approach to change `public class Products` to `public record Products` without changing other parts of the code ;) – Fabio Oct 22 '21 at 07:42
  • BTW, fields are implementation details even if they're public. They aren't considered part of an object's API/surface and won't be serialized by serializers like JSON.NET. Use properties instead – Panagiotis Kanavos Oct 22 '21 at 07:44
  • Every class etc. in C# implicitly inherits the `Object` class. Every object in C# has a `ToString` method, which returns a string representation of that object. For example, all variables of type int have a ToString method, which enables them to return their contents as a string. What you can do is, override the `ToString` method and return what you want. For e.x: you can serialize it. [reference](https://stackoverflow.com/questions/69673026/how-can-i-print-objects-to-the-console) – Ergis Oct 22 '21 at 07:45
  • Does this answer your question? [Override .ToString method c#](https://stackoverflow.com/questions/18200427/override-tostring-method-c-sharp) – Martheen Oct 22 '21 at 07:52

6 Answers6

5

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);
    }
}
Yong Shun
  • 35,286
  • 4
  • 24
  • 46
2

You can achieve the expect result by using System.Text.Json then do Console.WriteLine(JsonSerializer.Serialize(product))

Viettel Solutions
  • 1,519
  • 11
  • 22
  • I am using Visual Studio 2022 with .Net 4.8. So I was not able to use System.Text.Json (Element does not exist). You can externally link it with Nuget, or you use the better option (NewtonSoft.Json) - see my answer below. – pedda Jul 05 '23 at 18:21
1

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.

Ambotz
  • 121
  • 7
0

You cannot just print the class instance. Try to print the properties instead.

Console.WriteLine(product.productName);
Voodoo
  • 1,550
  • 1
  • 9
  • 19
0

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

Jakub Rusilko
  • 859
  • 12
  • 17
0

I am using Visual Studio 2022 with .Net 4.8. So I was not able to use System.Text.Json (Element does not exist) as above explained. I am aware of externally linking this library from NuGet, but as I am a great fan of the NewtonSoft.Json solution, I will use this here in my fully functional example.

Example: My example wants to make a printable version of my special Jira issue (atlassian issue tracker). I also make use of the JsonSerializer. Because the object is not "flat" and has loops inside, and also has some irrelevant but disturbingly high amount of data inside of a property ("Jira"), I wanted two things to achieve here:

  1. Printable Version of my object without having to access each property
  2. Excluding one complex property from getting serialized to Json
  3. Using flat structure and avoid circular references

So my method has a different signature with two arguments, and I am using the slightly different method JsonConvert. Here I can serialize my object easily, I can put a formatting - here to indented - (for printing out), and I can exclude loops and the "mother" object (in this case Jira). To make this excluding of the property 'Jira' working I use the 'IgnorePropertiesResolver : DefaultContractResolver' from this [solution][1]:

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using Atlassian.Jira;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace JIRA_SDK
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Task1();
            Console.ReadKey();
        }

        private async static void Task1()
        {
            var jira = Jira.CreateRestClient("URL", "user", "passw");

            // use LINQ syntax to retrieve issues
            var issues = from i in jira.Issues.Queryable
                         where i.Assignee == "user"
                         orderby i.Created
                         select i;

            foreach (var issue in issues)  
            {
                System.Console.WriteLine(JsonConvert.SerializeObject(issue, Formatting.Indented,
                        new JsonSerializerSettings()
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                        ContractResolver = new IgnorePropertiesResolver(new[] { "Jira" })
                    }));
            }*/

            Console.ReadKey();
        }
    }

    //short helper class to ignore some properties from serialization
    public class IgnorePropertiesResolver : DefaultContractResolver
    {
        private readonly HashSet<string> _ignoreProps;
        public IgnorePropertiesResolver(IEnumerable<string> propNamesToIgnore)
        {
            this._ignoreProps = new HashSet<string>(propNamesToIgnore);
        }

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);
            if (this._ignoreProps.Contains(property.PropertyName))
            {
                property.ShouldSerialize = _ => false;
            }
            return property;
        }
    }
}```


  [1]: https://stackoverflow.com/questions/63299905/custom-json-contract-resolver-to-ignore-all-properties-without-a-custom-annotation#answer-63305934
pedda
  • 106
  • 7