I have an XML file which has many children:
<Docs>
<Doc>
<DocType>x</DocType>
<DocNumber>xxx</DocNumber>
<DocNumberSeries>xx</DocNumberSeries>
<DocDate>xxxx-xx-xx</DocDate>
<DocCause>
<Id>xx</Id>
<Code/>
<Name>xx</Name>
</DocCause>
<Anag>
<Name>NameCompany</Name>
<Address>xx</Address>
<ZipCode>xx</ZipCode>
<City>xx</City>
<Province>xx</Province>
<CountryCode>xx</CountryCode>
<PhoneNumber>xx</PhoneNumber>
<CellularNumber/>
<FaxNumber>xx</FaxNumber>
<EmailAddress>xx</EmailAddress>
<VatNumber>xx</VatNumber>
<PersonalID>xx</PersonalID>
</Anag>
<DestinationAddress>
<Name>xxL</Name>
<Address>xx</Address>
<ZipCode>xx</ZipCode>
<City>xx</City>
<Province>xx</Province>
<CountryCode>xx</CountryCode>
<PhoneNumber>xx</PhoneNumber>
<FaxNumber>xx</FaxNumber>
</DestinationAddress>
<Payment>
<Code/>
<Name>xx</Name>
</Payment>
<DocRows>
<DocRow>
<RowType>1</RowType>
<Product>
<Code>LSML1710</Code>
</Product>
<Description></Description>
<Quantity></Quantity>
<Price></Price>
<Tax>
<Tax>
<Id>xx</Id>
<Code/>
<Name>xx</Name>
<PercentAmount>xx</PercentAmount>
<IndPercentAmount>x</IndPercentAmount>
<FixedAmount>x</FixedAmount>
</Tax>
</Tax>
</DocRow>
</DocRows>
...
</Doc>
For example, one of the thing I want to do is to get the data inside tag Doc and then Anag.
At the moment I have these classes:
public class Anag
{
public string RagioneSociale { get; set; }
public string Indirizzo { get; set; }
public string CAP { get; set; }
public string Citta { get; set; }
public string Provincia { get; set; }
public string CodiceNazione { get; set; }
public string Telefono { get; set; }
public string Cellulare { get; set; }
public string Email { get; set; }
}
public class Doc
{
public string DocNumber { get; set; }
public Anag Anags { get; set; }
}
List<Doc> results = contentFile.Descendants("Doc").Select(doc => new Doc // var results = contentFile.Descendants("Doc").SelectMany(doc => doc.Descendants(doc.Name.Namespace + "Anag").Select(anag => new
{
DocNumber = (string)doc.Element(doc.Name.Namespace + "DocNumber"),
Anags = doc.Descendants(doc.Name.Namespace + "Anag").Select(anag => new Anag
{
RagioneSociale = (string)anag.Element(anag.Name.Namespace + "Name"),
Indirizzo = (string)anag.Element(anag.Name.Namespace + "Address"),
CAP = (string)anag.Element(anag.Name.Namespace + "ZipCode"),
Provincia = (string)anag.Element(anag.Name.Namespace + "Province"),
Telefono = (string)anag.Element(anag.Name.Namespace + "PhoneNumber"),
Cellulare = (string)anag.Element(anag.Name.Namespace + "CellularNumber"),
Email = (string)anag.Element(anag.Name.Namespace + "EmailAddress"),
Citta = (string)anag.Element(anag.Name.Namespace + "City")
}),
}).ToList();
This last code gives an error:
Cannot implicitly convert type system.collections.generic.IEnumerable<nameProject.Classes.Anag> in <NameProject.Classes.Anag>.
The final result I want is a List with the data and children of this XML:
List:
+ Doc=>
{DocNumber}
+ Anag => { Address .. , Name.. .. ) (not a list ! )
+ DestinationAddress => { Address.... Name..)
so that I can convert to a file .csv only .
Since you already went through the trouble of creating the classes, why not let the deserializer do the job for you?
Here's how:
XmlSerializer serializer = new XmlSerializer(typeof(Root));
using (var reader = new StreamReader(xmlFilePath))
{
List<Doc> docs = ((Root)serializer.Deserialize(reader)).Docs;
}
Now, you just have to add some tags into your class properties so that they match the xml names.
[Serializable, XmlRoot("Docs")]
public class Root
{
[XmlElement("Doc")]
public List<Doc> Docs { get; set; }
}
public class Doc
{
public string DocNumber { get; set; }
[XmlElement("Anag")]
public Anag Anags { get; set; }
}
public class Anag
{
[XmlElement("Name")]
public string RagioneSociale { get; set; }
[XmlElement("Address")]
public string Indirizzo { get; set; }
[XmlElement("ZipCode")]
public string CAP { get; set; }
[XmlElement("City")]
public string Citta { get; set; }
[XmlElement("Province")]
public string Provincia { get; set; }
[XmlElement("CountryCode")]
public string CodiceNazione { get; set; }
[XmlElement("PhoneNumber")]
public string Telefono { get; set; }
[XmlElement("CellularNumber")]
public string Cellulare { get; set; }
[XmlElement("EmailAddress")]
public string Email { get; set; }
}
Just try using the feature "Paste Special" to generate the classes for parsing. You will 100% not get an exception.
Crtl + A on the whole xml, copy to clipboard
Then create a new class
in your project Click "Edit" -> "Paste Special" -> "Paste XML as
classes"
Change the parsing to use type of the "RootNode" in the
pasted class
Build and try it out.
Related
I have the following XML:
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
<accounts>
<items>
<account>
<voornaam><FirstName</voornaam>
<naam>LastName</naam>
<gebruikersnaam>Username</gebruikersnaam>
<internnummer></internnummer>
<klasnummer></klasnummer>
</account>
</items>
</accounts>
With these classes:
public class Accounts
{
public Accounts()
{
items = new List<Account>();
}
[XmlElement]
public List<Account> items { get; set; }
}
public class Account
{
public string voornaam { get; set; }
public string naam { get; set; }
public string gebruikersnaam { get; set; }
public int? internnummer { get; set; }
public int? klasnummer { get; set; }
}
And this code:
var decoded = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><accounts><items><account><voornaam>FirstName</voornaam><naam>LastName</naam><gebruikersnaam></gebruikersnaam><internnummer></internnummer><klasnummer></klasnummer></account></items></accounts>";
XmlSerializer serializer = new XmlSerializer(typeof(Accounts), new XmlRootAttribute("accounts"));
StringReader reader = new StringReader(decoded);
var accounts = (Accounts)serializer.Deserialize(reader);
All I get from this is an Accounts instance with the property Items containing one Account instance with every property null.
You need to specify the items as XML array with XmlArrayAttribute and also with the XmlArrayItemAttribute with (element) item's name: "account" and as Account type. XmlArrayAttribute Example.
public class Accounts
{
[XmlArrayItem(ElementName= "account",
Type = typeof(Account))]
[XmlArray(ElementName="items")]
public List<Account> items { get; set; }
}
Meanwhile, suggest using XmlElementAttribute to specify the element name in XML instead of naming the properties as camelCase.
For the reason why need InternnummerText and KlasnummerText properties you can refer to the question: Deserializing empty xml attribute value into nullable int property using XmlSerializer (will not cover in this answer).
public class Accounts
{
public Accounts()
{
Items = new List<Account>();
}
[XmlArrayItem(ElementName= "account",
Type = typeof(Account))]
[XmlArray(ElementName="items")]
public List<Account> Items { get; set; }
}
[XmlRoot(ElementName="account")]
public class Account
{
[XmlIgnore]
public int? Klasnummer { get; set; }
[XmlIgnore]
public int? Internnummer { get; set; }
[XmlElement(ElementName="voornaam")]
public string Voornaam { get; set; }
[XmlElement(ElementName="naam")]
public string Naam { get; set; }
[XmlElement(ElementName="gebruikersnaam")]
public string Gebruikersnaam { get; set; }
[XmlElement(ElementName="internnummer")]
public string InternnummerText
{
get { return (Internnummer.HasValue) ? Internnummer.ToString() : null; }
set { Internnummer = !string.IsNullOrEmpty(value) ? int.Parse(value) : default(int?); }
}
[XmlElement(ElementName="klasnummer")]
public string KlasnummerText
{
get { return (Klasnummer.HasValue) ? Klasnummer.ToString() : null; }
set { Klasnummer = !string.IsNullOrEmpty(value) ? int.Parse(value) : default(int?); }
}
}
Sample program
i've some problems when i'm trying to read a Yaml file using c# and need help to finish this task , how can i read a such Yaml file into variables so i can treat them .
FileConfig:
sourceFolder: /home
destinationFolder: /home/billy/my-test-case
scenarios:
- name: first-scenario
alterations:
- tableExtension: ln
alterations:
- type: copy-line
sourceLineIndex: 0
destinationLineIndex: 0
- type: cell-change
sourceLineIndex: 0
columnName: FAKE_COL
newValue: NEW_Value1
- tableExtension: env
alterations:
- type: cell-change
sourceLineIndex: 0
columnName: ID
newValue: 10
Here is my code
string text = System.IO.File.ReadAllText(#"test.yaml");
var deserializer = new Deserializer();
var result = deserializer.Deserialize<List<Hashtable>>(new StringReader(text));
/*foreach (var item in result)
{
Console.WriteLine("Item:");
Console.WriteLine(item.GetType());
foreach (DictionaryEntry entry in item)
{
Console.WriteLine("- {0} = {1}", entry.Key, entry.Value);
}
} */
The easiest way is to create a C# model of your document. Then you are able to use the Deserializer to fill that model with the data present into the document. A possible model for your document would be:
public class MyModel
{
[YamlMember(Alias = "FileConfig", ApplyNamingConventions = false)]
public FileConfig FileConfig { get; set; }
}
public class FileConfig
{
public string SourceFolder { get; set; }
public string DestinationFolder { get; set; }
public List<Scenario> Scenarios { get; set; }
}
public class Scenario
{
public string Name { get; set; }
public List<Alteration> Alterations { get; set; }
}
public class Alteration
{
public string TableExtension { get; set; }
public List<TableAlteration> Alterations { get; set; }
}
public class TableAlteration
{
public string Type { get; set; }
public int SourceLineIndex { get; set; }
public int DestinationLineIndex { get; set; }
public string ColumnName { get; set; }
public string NewValue { get; set; }
}
You can deserialize to that model as follows:
var deserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.Build();
var obj = deserializer.Deserialize<MyModel>(yaml);
You can run this code here: https://dotnetfiddle.net/SRABFM
Of course, the model that I suggest here is very naive and with more knowledge about your domain model, you will certainly be able to come up with a better one.
My XML
<?xml version="1.0" encoding="UTF-8"?>
<teklif>
<bilgiler>
<firma>Firma Adı</firma>
<aciklama>Açıklama</aciklama>
<isim>Ad Soyad</isim>
<telefon>Telefon</telefon>
<eposta>E Posta</eposta>
<urunler>
<urun>
<resimDosyasi>Dosya Seçilmedi</resimDosyasi>
<aciklama>Ürün Açıklaması</aciklama>
<birim>3,00</birim>
<miktar>1</miktar>
<toplam>0,00</toplam>
</urun>
<urun>
<resimDosyasi>Dosya Seçilmedi</resimDosyasi>
<aciklama>Ürün Açıklaması</aciklama>
<birim>5,00</birim>
<miktar>1</miktar>
<toplam>0,00</toplam>
</urun>
<urun>
<resimDosyasi>Dosya Seçilmedi</resimDosyasi>
<aciklama>aas</aciklama>
<birim>2,00</birim>
<miktar>1</miktar>
<toplam>0,00</toplam>
</urun>
</urunler>
And My Function which reads the XML file
XmlDocument doc = new XmlDocument();
doc.Load(filename);
XmlNodeList xmllist = doc.SelectNodes("/teklif/bilgiler/urunler");
foreach(XmlNode nod in xmllist)
{
foreach(XmlNode childNode in nod.ChildNodes)
{
// her ürünün childnode oldu
if(childNode.Name == "#text")
{
} else
{
var urun_resim = childNode.SelectSingleNode("//resimDosyasi").InnerText;
var urun_aciklama = childNode.SelectSingleNode("//aciklama").InnerText;
var urun_birim = childNode.SelectSingleNode("//birim").InnerText;
MessageBox.Show(urun_birim);
var urun_miktar = childNode.SelectSingleNode("//miktar").InnerText;
var urun_toplam = childNode.SelectSingleNode("//toplam").InnerText;
var urun = new Urun(urun_resim, urun_birim, urun_miktar, urun_aciklama);
lw_urunler.Items.Add(urun);
}
}
}
The problem is when I message box the //birim in foreach loop, it always writes the first one - 3,00((3 times). As you can see in XML, first is 3,00, the second is 5,00 and the third is 2,00 but it always writes the first one. I checked up a lot but I can't see the problem.
Try it without the //, e.g. childNode.SelectSingleNode("birim"). Two forward slashes mean the root of the XML document, and my guess is it's just always finding the first birim node starting from the root each time.
The // means to select nodes no matter where they are under the current context. Current context defaults to the root. To limit the results to those under the current child node follow this pattern (just add a dot):
var urun_resim = childNode.SelectSingleNode(".//resimDosyasi").InnerText;
Using xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication52
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<urun> uruns = doc.Descendants("urun").Select(x => new urun() {
resimDosyasi = (string)x.Element("resimDosyasi"),
aciklama = (string)x.Element("aciklama"),
birim = (string)x.Element("birim"),
miktar = (int)x.Element("miktar"),
toplam = (string)x.Element("toplam")
}).ToList();
}
}
public class urun
{
public string resimDosyasi { get; set; }
public string aciklama { get; set; }
public string birim { get; set; }
public int miktar { get; set; }
public string toplam { get; set; }
}
}
Another approach that would increase the readability and maintenance of your code would be to map the XML schema into an object model.
Doing so, you could easly load the XML data as follows:
XmlSerializer serializer = new XmlSerializer(typeof(Teklif));
using (FileStream fileStream = new FileStream(filename, FileMode.Open))
{
Teklif result = (Teklif)serializer.Deserialize(fileStream);
}
// Object model example
[XmlRoot("teklif")]
public class Teklif
{
[XmlElement()]
public bilgiler bilgiler { get; set; }
}
public class bilgiler
{
[XmlElement()] public string firma { get; set; }
[XmlElement()] public string aciklama { get; set; }
[XmlElement()] public string isim { get; set; }
[XmlElement()] public string telefon { get; set; }
[XmlElement()] public string eposta { get; set; }
[XmlArray()]
[XmlArrayItem("urun")]
public List<Urun> urunler { get; set; }
}
public class Urun
{
[XmlElement()] public string resimDosyasi { get; set; }
[XmlElement()] public string aciklama { get; set; }
[XmlElement()] public string birim { get; set; }
[XmlElement()] public int miktar { get; set; }
[XmlElement()] public string toplam { get; set; }
}
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I am currently pulling a httpwebrequest for warranty information. I have tested each section for information and it worked. Once I put it into a class it failed.
My question is, how can I effectively call the Device class ?
Dell computerRequest = new Dell(apiKey);
XDocument xlTest = new XDocument();
xlTest = computerRequest.XmlResponse(txtTag.Text.Trim());
XNamespace getAssetWarrantyA = "http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset";
XNamespace getAssetWarrantyI = "http://www.w3.org/2001/XMLSchema-instance";
List<Device> xlAsset = (from asset in xlTest.Descendants(getAssetWarrantyA + "Response")
select new Device()
{
DeviceInfo = (from defaultInfo in asset.Descendants(getAssetWarrantyA + "DellAsset")
select new DeviceBase()
{
Product = (string)asset.Descendants(getAssetWarrantyA + "MachineDescription").FirstOrDefault(),
OrderNumber = (string)asset.Descendants(getAssetWarrantyA + "OrderNumber").FirstOrDefault(),
ServiceTag = (string)asset.Descendants(getAssetWarrantyA + "ServiceTag").FirstOrDefault(),
ShipDate = (string)asset.Descendants(getAssetWarrantyA + "ShipDate").FirstOrDefault()
}).ToList(),
WarrantyInfo = (from warranty in asset.Descendants(getAssetWarrantyA + "Warranty")
select new Warranty()
{
Service = (string)warranty.Descendants(getAssetWarrantyA + "ServiceLevelDescription").FirstOrDefault(),
Provider = (string)warranty.Descendants(getAssetWarrantyA + "ServiceProvider").FirstOrDefault(),
StartDate = (string)warranty.Descendants(getAssetWarrantyA + "StartDate").FirstOrDefault(),
EndDate = (string)warranty.Descendants(getAssetWarrantyA + "EndDate").FirstOrDefault(),
TypeOfWarranty = (string)warranty.Descendants(getAssetWarrantyA + "EntitlementType").FirstOrDefault()
}).ToList(),
}).ToList();
**//FAILS -- No object set to reference**
Device testDevice = new Device();
MessageBox.Show(testDevice.WarrantyInfo.Count.ToString());
dtGrdWar.DataSource = xlAsset.ToArray();
}
public class Device
{
public List<DeviceBase> DeviceInfo{ get; set; }
public List<Warranty> WarrantyInfo { get; set; }
}
public class DeviceBase
{
public string Product { get; set; }
public string OrderNumber { get; set; }
public string ServiceTag { get; set; }
public string ShipDate { get; set; }
}
public class Warranty
{
public string Service { get; set; }
public string Provider { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string TypeOfWarranty { get; set; }
}
XML:
<GetAssetWarrantyResponse xmlns="http://tempuri.org/" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<GetAssetWarrantyResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:a="http://schemas.datacontract.org/2004/07/Dell.AWR.Domain.Asset">
<a:Faults/>
<a:Response>
<a:DellAsset>
<a:AssetParts i:nil="true"/>
<a:CountryLookupCode>11</a:CountryLookupCode>
<a:CustomerNumber>117731304</a:CustomerNumber>
<a:IsDuplicate>false</a:IsDuplicate>
<a:ItemClassCode>OC002</a:ItemClassCode>
<a:LocalChannel>66</a:LocalChannel>
<a:MachineDescription>COMPELLENT SC8000,1st,2nd,UPG</a:MachineDescription>
<a:OrderNumber>NANANANAN</a:OrderNumber>
<a:ParentServiceTag i:nil="true"/>
<a:ServiceTag>XXXXXXX</a:ServiceTag>
<a:ShipDate>2014-02-07T00:00:00</a:ShipDate>
<a:Warranties>
<a:Warranty>
<a:EndDate>2016-07-31T23:59:59</a:EndDate>
<a:EntitlementType>EXTENDED</a:EntitlementType>
<a:ItemNumber>933-5366</a:ItemNumber>
<a:ServiceLevelCode>S9</a:ServiceLevelCode>
<a:ServiceLevelDescription>4 Hour On-Site Service</a:ServiceLevelDescription>
<a:ServiceLevelGroup>5</a:ServiceLevelGroup>
<a:ServiceProvider>UNY</a:ServiceProvider>
<a:StartDate>2015-07-31T00:00:00</a:StartDate></a:Warranty>
<a:Warranty>
<a:EndDate>2016-07-31T23:59:59</a:EndDate>
<a:EntitlementType>EXTENDED</a:EntitlementType>
<a:ItemNumber>974-9929</a:ItemNumber>
<a:ServiceLevelCode>ZL</a:ServiceLevelCode>
<a:ServiceLevelDescription>CML - Storage Center Core Base</a:ServiceLevelDescription>
<a:ServiceLevelGroup>11</a:ServiceLevelGroup>
<a:ServiceProvider>DELL</a:ServiceProvider>
<a:StartDate>2015-07-31T00:00:00</a:StartDate></a:Warranty>
<a:Warranty>
<a:EndDate>2016-07-31T23:59:59</a:EndDate>
<a:EntitlementType>EXTENDED</a:EntitlementType>
<a:ItemNumber>933-5406</a:ItemNumber>
<a:ServiceLevelCode>SV</a:ServiceLevelCode>
<a:ServiceLevelDescription>Silver Premium Support</a:ServiceLevelDescription>
<a:ServiceLevelGroup>8</a:ServiceLevelGroup>
<a:ServiceProvider>DELL</a:ServiceProvider>
<a:StartDate>2015-07-31T00:00:00</a:StartDate></a:Warranty>
<a:Warranty>
<a:EndDate>2015-07-31T23:59:59</a:EndDate>
<a:EntitlementType>EXTENDED</a:EntitlementType>
<a:ItemNumber>933-5416</a:ItemNumber>
<a:ServiceLevelCode>SV</a:ServiceLevelCode>
<a:ServiceLevelDescription>Silver Premium Support</a:ServiceLevelDescription>
<a:ServiceLevelGroup>8</a:ServiceLevelGroup>
<a:ServiceProvider>DELL</a:ServiceProvider>
<a:StartDate>2014-08-01T00:00:00</a:StartDate></a:Warranty>
<a:Warranty>
<a:EndDate>2015-07-31T23:59:59</a:EndDate>
<a:EntitlementType>EXTENDED</a:EntitlementType>
<a:ItemNumber>933-5376</a:ItemNumber>
<a:ServiceLevelCode>S9</a:ServiceLevelCode>
<a:ServiceLevelDescription>4 Hour On-Site Service</a:ServiceLevelDescription>
<a:ServiceLevelGroup>5</a:ServiceLevelGroup>
<a:ServiceProvider>UNY</a:ServiceProvider>
<a:StartDate>2014-08-01T00:00:00</a:StartDate></a:Warranty>
<a:Warranty>
<a:EndDate>2015-07-31T23:59:59</a:EndDate>
<a:EntitlementType>EXTENDED</a:EntitlementType>
<a:ItemNumber>975-0042</a:ItemNumber>
<a:ServiceLevelCode>ZL</a:ServiceLevelCode>
<a:ServiceLevelDescription>CML - Storage Center Core Base</a:ServiceLevelDescription>
<a:ServiceLevelGroup>11</a:ServiceLevelGroup>
<a:ServiceProvider>DELL</a:ServiceProvider>
<a:StartDate>2014-08-01T00:00:00</a:StartDate></a:Warranty>
<a:Warranty>
<a:EndDate>2014-07-31T23:59:59</a:EndDate>
<a:EntitlementType>EXTENDED</a:EntitlementType>
<a:ItemNumber>933-5376</a:ItemNumber>
<a:ServiceLevelCode>S9</a:ServiceLevelCode>
<a:ServiceLevelDescription>4 Hour On-Site Service</a:ServiceLevelDescription>
<a:ServiceLevelGroup>5</a:ServiceLevelGroup>
<a:ServiceProvider>UNY</a:ServiceProvider>
<a:StartDate>2014-02-07T00:00:00</a:StartDate></a:Warranty></a:Warranties></a:DellAsset></a:Response></GetAssetWarrantyResult></GetAssetWarrantyResponse>
The issue was with the class being created correctly. Here is the correction for anyone that is curious:
public class Device
{
private List<DeviceBase> _deviceInfo = new List<DeviceBase>();
private List<Warranty> _warrantyInfo = new List<Warranty>();
public List<DeviceBase> DeviceInfo
{
get
{ return _deviceInfo; }
set
{ _deviceInfo = value; }
}
public List<Warranty> WarrantyInfo
{
get
{ return _warrantyInfo; }
set
{ _warrantyInfo = value; }
}
}
public class DeviceBase
{
public string Product { get; set; }
public string OrderNumber { get; set; }
public string ServiceTag { get; set; }
public string ShipDate { get; set; }
}
public class Warranty
{
public string Service { get; set; }
public string Provider { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string TypeOfWarranty { get; set; }
}
I have an application that will parse an excel file and add a column, then generate a new CSV file with the results. I am able to create a list of the items I want in the file, but I cannot figure out how to pass that list to the method that is generating the new file.
I have the following class:
public class LocationData
{
public string PostalCode { get; set; }
public string Partner { get; set; }
public string LocationID { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Market { get; set; }
}
and the following code to get the data into a list:
LocationData Locationdata = new LocationData()
{
PostalCode = location[0],
Partner = location[1],
LocationID = location[2],
Name = location[3],
Country = location[4],
Market = repository.GetMarketsForPostalCode(location[0])
}
I also have the method to create the csv and I need to pass in the list info, but I get the error:
foreach statement cannot operate on variables of type 'app.LocationData' because 'app.LocationData' does not contain a public definition for 'GetEnumerator'
I think you are misunderstanding what a list is in C#. I think you need the List data type. Try this:
List<string> Locationdata = new List<string>()
{
location[0],
location[1],
location[2],
location[3],
location[4],
repository.GetMarketsForPostalCode(location[0])
};
Your csv function will look like this
public void GenerateCSV(List<LocationData> data)
{
foreach (LocationData d in data)
{
//put line in csv as
string s = d.PostalCode + "," d.Partner + _"," + d.LocationID...... + Environment.NewLine;
}
}
Your class declaration will remain same
public class LocationData
{
public string PostalCode { get; set; }
public string Partner { get; set; }
public string LocationID { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Market { get; set; }
}
Now you need to add all the data in the list first
which you will do like this
List<LocationData> lst = new List<LocationData>();
LocationData ld = new LocationData();
ld.LocationID = "0";
ld.Market = "market";
lst.Add(ld);
........
GenerateCSV(lst);