C# List of Objects - c#

I'm not sure how to create a list of objects. I get "Non-invocable member ListObjects.TestObject.UniqueID' cannot be used like a method."
Any insight would be helpful.
The code for the object I'm trying to create a list of:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListObjects
{
class TestObject
{
public int UniqueID { get; set; }
}
}
Main code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListObjects
{
class Program
{
static void Main(string[] args)
{
TestObject TestObject = new TestObject();
List<TestObject> ObjectList = new List<TestObject>();
ObjectList.Add(new TestObject().UniqueID(1));
ObjectList.Add(new TestObject().UniqueID(10));
ObjectList.Add(new TestObject().UniqueID(39));
}
}
}

public int UniqueID { get; set; } is not a method its a setter and you use it like a method
do this
ObjectList.Add(new TestObject()
{
UniqueID = 1
});

I cannot rememer the syntax but it is from memory:
repalce this line:
ObjectList.Add(new TestObject().UniqueID(1));
with this line:
ObjectList.Add(new TestObject(){UniqueID = 1});
and do the same for all .Add lines you have.

You are using UniqueId like a method. It is a property and must be assigned. If you know you'll be assigning an ID when creating a TestObject, you should make the constructor support that, and use it accordingly. If not, use ObjectList.Add(new TestObject { UniqueID = 1 }); to assign the value without a constructor.
This is how I would handle the situation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListObjects
{
class TestObject
{
public int UniqueID { get; set; }
public TestObject(int uniqueId)
{
UniqueID = uniqueId;
}
}
}
Main code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListObjects
{
class Program
{
static void Main(string[] args)
{
List<TestObject> ObjectList = new List<TestObject>();
ObjectList.Add(new TestObject(1));
ObjectList.Add(new TestObject(10));
ObjectList.Add(new TestObject(39));
}
}
}

There's a couple of things going on here. You don't need an instance of the object to declare the list, just the type.
Also, UniqueID is a property, not a method. You assign values to them (or read values from them), you don't pass in values like a parameter for a method.
You can also initialize the list in one call, like this:
List<TestObject> ObjectList = new List<TestObject>()
{ new TestObject() { UniqueID = 1},
new TestObject() { UniqueID = 10 },
new TestObject() { UniqueID = 39 } };
This will result in a new List<T> where T is of type TestObject, and the list is initialized to 3 instances of TestObject, with each instance initialized with a value for UniqueID.

TestObject TestObject = new TestObject();
Remove this line.
And edit following lines to this syntax
new TestObject { UniqueID = 39 }

Related

How to return an XML element value from a Descendant when passing in another element value from that Descendant

I am new to working with LINQ to XML, but I can see how it could be helpful to my current problem. I want a method that you pass in an XML Document and an Element value, the method would then return a different Element Value from the same Descendant. For example if I provided a "StationName" I would like to know what "ScannerType" belongs to that "StationName"
Here is my XML
<?xml version="1.0" encoding="utf-8" ?>
<stations>
<station>
<stationName>CH3CTRM1</stationName>
<scannerType>GE LightSpeed VCT</scannerType>
<scannerID>COL02</scannerID>
<siteName>CUMC</siteName>
<inspDose>180</inspDose>
<expDose>100</expDose>
<kernel>STANDARD</kernel>
</station>
<station>
<stationName>CTAWP75515</stationName>
<scannerType>SIEMENS Force</scannerType>
<scannerID>UIA07</scannerID>
<siteName>Iowa</siteName>
<inspDose>careDose</inspDose>
<expDose>careDose</expDose>
<kernel>Qr40 5</kernel>
</station>
<station>
<stationName>JHEB_CT06N_JHOC2</stationName>
<scannerType>SIEMENS Force</scannerType>
<scannerID>JHU04</scannerID>
<siteName>JHU</siteName>
<inspDose>careDose</inspDose>
<expDose>careDose</expDose>
<kernel>Qr40 5</kernel>
</station>
</stations>
Here are the methods that are currently in question
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace ManualPhantomProcessor.XMLParser
{
class SearchXML
{
public string filename = "SiteData.xml";
public string currentDirectory = Directory.GetCurrentDirectory();
public XDocument LoadXML()
{
string siteDataFilePath = Path.Combine(currentDirectory, filename);
XDocument siteData = XDocument.Load(siteDataFilePath);
return siteData;
}
public IEnumerable<string> GetScannerModel(XDocument xmlDocument, string stationName)
{
var query = xmlDocument.Descendants("station")
.Where(s => s.Element("stationName").Value == stationName)
.Select(s => s.Element("scannerType").Value)
.Distinct();
return query;
}
}
}
Here is my Programs.cs file
using ManualPhantomProcessor.XMLParser;
using System;
using System.Collections.Generic;
using System.Xml.Linq;
namespace ManualPhantomProcessor
{
class Program
{
static void Main(string[] args)
{
SearchXML searchXML = new SearchXML();
XDocument siteData = searchXML.LoadXML();
IEnumerable<string> data = searchXML.GetScannerModel(siteData, "CH3CTRM1");
Console.WriteLine(data);
}
}
}
I should be a simple console application, but it seem like no matter what I try I keep getting a null value when I expect the scannerType value from the XML document that corresponds with the station name "CH3CTRM1"
the application doesn't crash but in my console I get the following:
System.Linq.Enumerable+DistinctIterator`1[System.String]
Could explain what I am doing incorrectly?
Your code is good, the problem is here Console.WriteLine(data); the WriteLine take string like a parameter not a list of string. to display the station names use a loop, like the following code :
foreach(string stationName in data)
{
Console.WriteLine(stationName);
}
The documentation of WriteLine
i hope that will help you fix the issue.
What you're seeing is the string form of the IEnumerable<string> returned by GetScannerModel().
There are two possibilities:
Only one scanner model is expected to be found (because a station name is expected
to be unique).
Any number of scanner models can be found.
In the first case, change GetScannerModel() to return a string and have it do soemthing like return query.FirstOrDefault(); (or .First() if you want an exception if no match was found). Your client program then remains unchanged.
In the second case, #Sajid's answer applies - you need to enumerate the IEnumerable in some way, for example through foreach.
Use a dictionary :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<Station> stations = doc.Descendants("station").Select(x => new Station
{
stationName = (string)x.Element("stationName"),
scannerType = (string)x.Element("scannerType"),
scannerID = (string)x.Element("scannerID"),
siteName = (string)x.Element("siteName"),
inspDose = (string)x.Element("inspDose"),
expDose = (string)x.Element("expDose"),
kernel = (string)x.Element("kernel")
}).ToList();
Dictionary<string, Station> dict = stations
.GroupBy(x => x.stationName, y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
}
}
public class Station
{
public string stationName {get;set;}
public string scannerType {get;set;}
public string scannerID {get;set;}
public string siteName {get;set;}
public string inspDose {get;set;}
public string expDose {get;set;}
public string kernel { get; set; }
}
}

How to store values of different types in a single Structure

I have a text file in that has a list of strings (Example 6|Chicago|Illinois|I-98;I-90). I am trying to create two Classes. One class (CityReader) reads the text file and other file prints it. I declared a class(CityItem) with 4 variables, int population, string city, string state, List<int> Interstates.
In the CityReader class I created a CityItem Object(CIObj) and was able to read the file and delimit it and returning CIObj. But when I access this object from a different class I am only seeing the last line in the text file. This object is not returning all the values.
I realized though I am reading the file in each loop. I am not storing those values and hence the object is holding only the last object.
CityItem Class-----
using System;
using System.Collections.Generic;
using System.Text;
namespace ReadingAtxtFile
{
public class CityItem
{
public int Population { get; set; }
public string City { get; set; }
public string State { get; set; }
public List<int> Interstates = new List<int>();
}
}
CityReader Class-----
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
namespace ReadingAtxtFile
{
public class CityReader
{
public CityItem ReadCities(string FilePath)
{
CityItem CIObj = new CityItem();
var AllLines = File.ReadAllLines(FilePath, Encoding.UTF8);
try
{
foreach (var item1 in AllLines)
{
string[] EachLine = item1.Split('|');
CIObj.Population = Convert.ToInt32(EachLine[0]);
CIObj.City = EachLine[1];
CIObj.State = EachLine[2];
string[] IStates = EachLine[3].Split(';');
foreach (var item2 in IStates)
{
var IStatesAfterSplit = item2.Split("-");
CIObj.Interstates.Add(Convert.ToInt32(IStatesAfterSplit[1]));
}
}
}
catch (Exception)
{
Console.WriteLine("There is an issue with processing the data");
}
return CIObj;
}
}
}
Input TextFile:
6|Oklahoma City|Oklahoma|I-35;I-44;I-40
6|Boston|Massachusetts|I-90;I-93
8|Columbus|Ohio|I-70;I-71
I am trying to process the text file and print the data as I like. For example. population
Population,
City, State,
Interstates: I-35,I-40,I-45 (Sorted order)
Your ReadCities method needs to return some kind of collection of CityItem objects, not just a single CityItem object. .Net supports various kinds of collections, but a List is probably best for this instance.
Then, after populating your CityItem object, before moving to the next iteration of the loop, add the CityItem object to your List. Something like...
List<CityItem> listOfCityItems = new List<CityItem>();
foreach (var line in AllLines)
{
CityItem ci = new CityITem();
// Populate the properties of ci
listOfCityItems.Add(ci);
}

XML Serializing list of objects containing list of objects

My object structure is similar to the simplified code below. Please note that both Countries and Cars need to be classes, I can't use string list/array due to code not included in sample. I want to XML serialize and later deserialize the objects.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace XMLapp
{
public partial class Form1 : Form
{
List<Countries> Country = new List<Countries>();
List<string> cars = new List<string>();
public Form1()
{
InitializeComponent();
cars.Add("Audi");
cars.Add("BMW");
cars.Add("Mercedes");
addCountry("Germany", cars);
cars.Clear();
cars.Add("Ford");
cars.Add("Chevrolet");
cars.Add("Jeep");
addCountry("USA", cars);
TestXmlSerialize();
Console.WriteLine("Generated list");
}
void TestXmlSerialize()
{
XmlSerializer x = new XmlSerializer(Country.GetType());
x.Serialize(Console.Out, Country);
}
void addCountry(string name, List<string> cars)
{
Countries newCountry = new Countries();
newCountry.Name = name;
newCountry.AddCar(cars);
Country.Add(newCountry);
}
}
public class Countries
{
public string Name { get; set; }
List<Cars> car = new List<Cars>();
public void AddCar(List<string> cars)
{
for (int i = 0; i < cars.Count; i++)
{
Cars newCar = new Cars();
newCar.brand = cars[i];
car.Add(newCar);
}
}
class Cars
{
public string brand;
}
}
}
This generates following output:
<?xml version="1.0" encoding="IBM437"?>
<ArrayOfCountries xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Countries>
<Name>Germany</Name>
</Countries>
<Countries>
<Name>USA</Name>
</Countries>
</ArrayOfCountries>
However, I expected something along the lines of
<Countries>
<Name>Germany</Name>
<ArrayOfCars>
<Brand>Audi</Brand>
<Brand>BMW</Brand>
<Brand>Mercedes</Brand>
</ArrayOfCountries>
</Countries>
I can see that the car brands are stored properly in the Locals & Autos window, but how do I include them in the serialization?
XmlSerializer only serializes public fields and properties. You need to make the 'car' field and the class 'Cars' public.
It won't produce the exact xml layout that you posted in your question, but it will let you serialize and deserialize the object.

Binding multidimensional JSON array in windows phone 8

I have a json response like below code, and need to know how can i handle this with my current setup,
currently i can handle only one pair value-key response(id=type),
please refer the code i cant output these to a long list selector
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp5.Resources;
using Newtonsoft.Json;
namespace PhoneApp5
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
var definition1 = new { Name = "" };
var definition2 = new { id = "" }; //is that true? i want to pull inside the Table1
string json1 = #"{'Name':'James'}";
string json2 = #"{
'Table1': [
{
'id': 0,
'item': 'item 0'
},
{
'id': 1,
'item': 'item 1'
}
]
}";
var example1 = JsonConvert.DeserializeAnonymousType(json1, definition1);
var example2 = JsonConvert.DeserializeAnonymousType(json2, definition2);
MessageBox.Show(example2.id);
// ??? i need to do with a long list selector
}
}
}
As you edited your answer, you can do something like this:
public class MyClass
{
public string Id { get; set; }
public string Item { get; set; }
}
Then, do this:
var myClassList = JsonConvert.DeserializeObject<List<MyClass>>(e.Result);
longListSelector.ItemsSource = myClassList;
That way you're binding your class list to the LongListSelector Control.

"Not all code paths return a value" C#

Hello i am currently in the infant stages of writing a petshop app on Windows phone/C#. I have made the class below to set up my generic lists and to be able to add the pets to the shop using the given fields ( Name, age, breed and type ). The problem i believe lies in the fact that i am making a display method to be called (in another page which is below called Mainpage.xaml.cs) below called DisplayShop() and i am reading in 3 strings and an int, i believe it has something to do with the fact that my DisplayShop() method is a string, although i tried to rectify the problem by converting the age field to a string in the Display() method, although this has not fixed the problem.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assignment_1
{
public class Shop
{
private string name;
private int age;
private string breed;
private string type;
public Shop(string Name, int Age, string breed, string Type)
{
this.Name = name;
this.Age = age;
this.breed = breed;
this.Type = type;
}
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
public int Age
{
get
{
return this.age;
}
set
{
this.age = value;
}
}
public string Breed
{
get
{
return this.breed;
}
set
{
this.breed = value;
}
}
public string Type
{
get
{
return this.type;
}
set
{
this.type = value;
}
}
//Create the Collection
List<Shop> myShop = new List<Shop>();
public String Display()
{
return (Name + "\n" + Age.ToString() + "\n" + Breed + "\n" + Type);
}
public String DisplayShop()
{
foreach (Shop tmp in myShop)
{
tmp.Display();
}
}
}
}
Here is the Mainpage.xaml.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace Assignment_1
{
public partial class MainPage : PhoneApplicationPage
{
List<Shop> myShop = new List<Shop>();
// Constructor
public MainPage()
{
InitializeComponent();
setUpShop();
}
//Add animals to the Shop
private void setUpShop()
{
myShop.Add(new Shop("John", 3 ,"Labrador", "Dog"));
myShop.Add(new Shop("Billy", 9, "Terrier", "Dog"));
myShop.Add(new Shop("Sam", 2, "Persian", "Cat"));
myShop.Add(new Shop("Molly", 3, "Siamese", "Cat"));
myShop.Add(new Shop("Nemo", 1, "Clown Fish", "Fish"));
myShop.Add(new Shop("Dory", 1, "Palette Surgeonfish", "Fish"));
myShop.Add(new Shop("Keith", 1, "Bearded Dragon", "Lizard"));
myShop.Add(new Shop("Ozzy", 1, "Gecko", "Lizard"));
imgHolder1.Items.Add(myShop[1].DisplayShop());
}
}
}
The aim of this first part is to add the pets to an listBox in my windows app, if any of you could suggest a fix to this problem it would be much appreciated, I have included an image of the the way the phone app currently looks >>> http://gyazo.com/06217efae9265d0fef59cd2a44be7923 and the error code >>> http://gyazo.com/40c47628f1dfb7d735af4c72dde3a651
Thanks in advance,
Jason
Looks like you forgot to return value from DisplayShop funcion:
public String DisplayShop()
{
List<string> shops = new List<string>();
foreach (Shop tmp in myShop)
{
shops.Add(tmp.Display());
}
return string.Join(",", shops);
}
Join used here just to show the general idea, you can use whatever you want to construct the whole string.
You are not returning anything from this function:
public String DisplayShop()
You should return a string from it, or just change return type to void if you don't want to return anything:
public void DisplayShop()
Update:
imgHolder1.Items.Add(myShop[1].DisplayShop());
In this line you are calling DisplayShop on a Shop instance,but you didn't add any elements to the list that is inside of the Shop class.You create a seperate list.So in this case even if it works myShop[1].DisplayShop() won't display anything because your initial myShop list is empty.If you want to display one Shop just call your Display method.Anyway,probably you don't need that initial list, if you want to add all Shops to the listBox then use a simple foreach loop:
foreach(var shop in myShop)
{
imgHolder1.Items.Add(shop.Display());
}
public String DisplayShop()
{
foreach (Shop tmp in myShop)
{
tmp.Display();
}
}
your return type is a String but you aren't returning anything. Not all code paths return a value is telling you exactly that

Categories

Resources