I have list in class
public List<Igrac> Igraci { get; set; } = new List<Igrac>();
The class:
class Igrac
{
public string Ime { get; set; }
public string Prezime { get; set; }
public string Pozicija { get; set; }
public int Godine { get; set; }
public Igrac(string Ime, string Prezime, string Pozicija, int Godine)
{
this.Ime = Ime;
this.Prezime = Prezime;
this.Pozicija = Pozicija;
this.Godine = Godine;
}
}
Added new list elements:
noviklb.DodavanjeIgraca(new Igrac("Petar", "Petrovic", "Krilo", 1992));
noviklb.DodavanjeIgraca(new Igrac("Badr", "Hari", "Napad", 1993));
The method for adding is working OK. The problem is that when I use Console.WriteLine I get an error like this:
System.Collections.Generic.List`1[zadatak.Program+Igrac]
I Googled and foreach is solution but I cant do it right. Do I need to write foreach as method?
class Igrac
{
public string Ime { get; }
public string Prezime { get; }
public string Pozicija { get; }
public int Godine { get; }
public Igrac(string Ime, string Prezime, string Pozicija, int Godine)
{
this.Ime = Ime;
this.Prezime = Prezime;
this.Pozicija = Pozicija;
this.Godine = Godine;
}
}
public override string ToString()
{
return $"{Ime} {Prezime} {Pozicija} {Godine}";
}
Now you can use.
string myStringDate = new Igrac("Petar", "Petrovic", "Krilo", 1992).ToString();
ALSO NOTE: It would be good to make you properties get only.
Working link:
https://dotnetfiddle.net/zMNiln
use this code:
public void showList(List<Igrac> noviklb)
{
foreach (var item in noviklb)
{
Console.WriteLine("Ime : " + item.Ime);
Console.WriteLine("Prezime : " + item.Prezime);
Console.WriteLine("Pozicija : " + item.Pozicija);
Console.WriteLine("Godine : " + item.Godine);
Console.WriteLine("Get New Record****************** ");
}
}
Related
I am using the Caliburn.Micro MVVM pattern.
I am writing an application that has 2 DataGrids, one holds a BindableCollection of RepairOrder, the other a BindableCollection WriteOff.
BindableCollection_WriteOff is property of BindableCollection_RepairOrder. (See the below code).
I need to find a way to write all the RepairOrder including the WriteOff associated with each RO. Besides RepairOrder class holding the WriteOff class, the WriteOff class does not have a way to tie the WriteOff to a RepairOrder.
Repair Order Class:
public class RepairOrder
{
public string Schedule { get; set; }
public string ControlNumber { get; set; }
public int Age { get; set; }
public double Value { get; set; }
public string Note { get; set; }
public double OrgValue { get; set; }
private List<WriteOff> _myWriteOffs;
public List<WriteOff> GetMyWriteOffs()
{
return _myWriteOffs;
}
public void AddMyWriteOff(WriteOff value)
{ _myWriteOffs.Add(value); }
public void DeleteMyWriteOff(WriteOff value)
{ _myWriteOffs.Remove(value); }
public RepairOrder(string CN, string SC, double VL)
{
ControlNumber = CN;
Schedule = SC;
Value = Math.Round(VL, 2);
Note = null;
_myWriteOffs = new List<WriteOff>();
}
public RepairOrder()
{
_myWriteOffs = new List<WriteOff>();
}
public static RepairOrder FromCSV(string CSVLine, string Sched)
{
string[] values = CSVLine.Split(',');
RepairOrder rep = new RepairOrder();
rep.ControlNumber = values[2];
rep.Value = Math.Round(double.Parse(values[5]),2);
rep.Age = int.Parse(values[4]);
rep.Schedule = Sched;
return rep;
}
}
Write Off Class:
public class WriteOff
{
private string _store;
public string Account { get; set; }
public string Description { get; set; }
public double WriteOffAmount { get; set; }
public string Schedule { get; set; }
public string Store
{
get {
if (String.IsNullOrEmpty(_store)) return "";
string temp = _store.Substring(0, 3);
return temp;
}
set { _store = value; }
}
public string Note { get; set; }
public WriteOff(string Acct, string Desc, double Amount, string _store)
{
Account = Acct;
Description = Desc;
WriteOffAmount = Amount;
Store = _store;
}
public string GetWOAccount() {
string SchedAccountNumber = "";
//{ "Navistar", "Cummins", "Misc", "Kenworth", "Mack/Volvo" }
switch (Account)
{
case "Navistar":
SchedAccountNumber = "222000";
break;
case "Cummins":
SchedAccountNumber = "223000";
break;
case "Misc":
SchedAccountNumber = "224500";
break;
default:
SchedAccountNumber = "";
break;
}
return SchedAccountNumber;
}
}
ANSWER:
Changed the class as suggested by Tim and it worked like a charm.
public class DatiBeniServizi1
{
[XmlElement]
public List<DettaglioLinee> DettaglioLinee { get; set; }
public DatiRiepilogo1 DatiRiepilogo { get; set; }
}
I'm trying to create an XML using a class. Below is the class
public class DatiBeniServizi1
{
public List<DettaglioLinee> DettaglioLinee { get; set; }
public DatiRiepilogo1 DatiRiepilogo { get; set; }
}
public class DettaglioLinee
{
public int NumeroLinea { get; set; }
public string Descrizione { get; set; }
public int Quantita { get; set; }
public decimal PrezzoUnitario { get; set; }
public decimal PrezzoTotale { get; set; }
public decimal AliquotaIVA { get; set; }
public string Natura { get; set; }
}
public class DatiRiepilogo1
{
public decimal AliquotaIVA { get; set; }
public string Natura { get; set; }
public decimal ImponibileImporto { get; set; }
public decimal Imposta { get; set; }
public string RiferimentoNormativo { get; set; }
}
and the code to generate XML
private DatiBeniServizi1 GetXMLExportInvoiceItemDetails(DataTable dtItemDetails, DataTable dtBatches)
{
DatiBeniServizi1 DatiBeniServizi12 = new DatiBeniServizi1();
List<DettaglioLinee> ItemDetails = new List<DettaglioLinee>();
int i = 1;
foreach (DataRow row in dtItemDetails.Rows)
{
DataRow[] rowList = dtBatches.Select("BatchItemID='" + row["ItemID"].ToString() + "'");
string BatchDetails = string.Empty;
if (rowList.Any())
{
foreach (DataRow dr in rowList)
{
BatchDetails = BatchDetails + " - " + "Batch No: " + dr["BatchNo"].ToString() + " Exp: " + Convert.ToDateTime(dr["Expiry Date"]).ToString("dd/MM/yy");
}
}
ItemDetails.Add(new DettaglioLinee
{
NumeroLinea = i,
Descrizione = row["Description"].ToString() + BatchDetails,
Quantita = Convert.ToInt32(row["Qty"]),
PrezzoUnitario = Convert.ToDecimal(row["Sell Price"]),
PrezzoTotale = Convert.ToDecimal(row["Amount"]),
AliquotaIVA = 0.00m,
Natura = "N4"
});
i++;
}
DatiBeniServizi12 = new DatiBeniServizi1
{
DettaglioLinee = ItemDetails,
DatiRiepilogo = new DatiRiepilogo1
{
AliquotaIVA = 0.00m,
Natura = "N4",
ImponibileImporto = Convert.ToDecimal(gvQuotationDetails.Rows[QuoteIndex].Cells["TotalQuoteAmount"].EditedFormattedValue),
Imposta = 0.00m,
RiferimentoNormativo = "rif normativo"
}
};
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("xsd", "http://www.w3.org/2001/XMLSchema");
ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
ns.Add("versione", "FPA12");
XmlSerializer serializer = new XmlSerializer(typeof(FatturaElettronica), "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2");
serializer.Serialize(System.IO.File.Create(#"C:\JD Pics\Schema_fatturapa_v1.3.xml"),DatiBeniServizi12,ns);
}
Final Output is
<DatiBeniServizi>
**<DettaglioLinee>
<DettaglioLinee>**
<NumeroLinea>1</NumeroLinea>
<Descrizione>ACARBOSE TAB 100MG 90 - Batch No: 854697 Exp: 15/11/20</Descrizione>
<Quantita>5</Quantita>
<PrezzoUnitario>30.50</PrezzoUnitario>
<PrezzoTotale>152.50</PrezzoTotale>
<AliquotaIVA>0.00</AliquotaIVA>
<Natura>N4</Natura>
</DettaglioLinee>
<DettaglioLinee>
<NumeroLinea>2</NumeroLinea>
<Descrizione>AEROCHAMBER PLUS DEVICE INFANT/MASK - Batch No: 748569 Exp: 23/11/20 - Batch No: 45789 Exp: 23/11/20</Descrizione>
<Quantita>400</Quantita>
<PrezzoUnitario>1.13</PrezzoUnitario>
<PrezzoTotale>452.00</PrezzoTotale>
<AliquotaIVA>0.00</AliquotaIVA>
<Natura>N4</Natura>
**</DettaglioLinee>
</DettaglioLinee>**
<DatiRiepilogo>
<AliquotaIVA>0.00</AliquotaIVA>
<Natura>N4</Natura>
<ImponibileImporto>604.50</ImponibileImporto>
<Imposta>0.00</Imposta>
<RiferimentoNormativo>rif normativo</RiferimentoNormativo>
</DatiRiepilogo>
</DatiBeniServizi>
So from the above XML everything is fine as per our requirement except the one highlighted in **
<DettaglioLinee>
<DettaglioLinee>
As you can see the node is repeated which is not the requirement.
This should work. It causes the list to be output in a flat structure - without the enclosing DettaglioLinee elements
[XmlElement]
List<DettaglioLinee> ItemDetails = new List<DettaglioLinee>();
First, i'm a beginning in c#. I'm try to code some game. I don't know how to return enum value as string.
Here my code.
public class CARDS {
public CARDS(int id, int atk, ClassType ctype, string name) {
this.CARD_ID = id;
this.C_TYPE = ctype;
this.ATK = atk;
this.NAME_EN = name;
}
public CARDS() {
this.CARD_ID = -1;
}
public int CARD_ID { get; set; }
public ClassType C_TYPE { get; set; }
public int ATK { get; set; }
public string NAME_EN { get; set; }
public enum ClassType {
Warrior,
Mage,
Archer,
Thief,
Bishop,
Monk,
Guardian,
Destroyer,
Chaser,
Hermit,
Alchemy
}
}
.......
Here I try to do.
public class CardCollection : MonoBehaviour {
private List<CARDS> dbase = new List<CARDS>();
private JsonData cardsdata;
private JsonData card;
void Start() {
cardsdata = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/Json/card.json"));
ConstructCardData();
Debug.Log(dbase[1].NAME_EN + " " + dbase[23].NAME_EN);
}
void ConstructCardData() {
card = cardsdata["CARDS"];
for (int i = 0; i < card.Count; i++) {
dbase.Add(new CARDS((int)card[i]["CARD_ID"], (int)card[i]["ATK"], card[i]["C_TYPE"].ToString(), card[i]["NAME_EN"].ToString()));
}
}
}
// card[i]["C_TYPE"].ToString()
It say can't convert from string to CARDS.ClassType
What about :
public class CARDS
{
public CARDS(int id, int atk, ClassType ctype, string name)
{
this.CARD_ID = id;
this.C_TYPE = Enum.GetName(ctype.GetType(), ctype); //Use Enum.GetName to get string
this.ATK = atk;
this.NAME_EN = name;
}
public CARDS()
{
this.CARD_ID = -1;
}
public int CARD_ID { get; set; }
public string C_TYPE { get; set; } //change type to string
public int ATK { get; set; }
public string NAME_EN { get; set; }
public enum ClassType
{
Warrior,
Mage,
Archer,
Thief,
Bishop,
Monk,
Guardian,
Destroyer,
Chaser,
Hermit,
Alchemy
}
}
ToString() on the enum values return the string value of the enum. Custom string values can also be returned for the enum values, check these links, link1 , link2
Examples:
ClassType.Warrior.ToString();
ctype.ToString();
I have this:
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
public List<???prpClass???> Whatever(string prpClass)
where string prpClass can be "Blah" or "Doh".
I would like the List type to be class Blah or Doh based on what the string prpClass holds.
How can I achieve this?
EDIT:
public List<prpClass??> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result;
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result;
}
return null
}
}
you have to have a common supertype:
public interface IHaveAnId
{
int id { get;set; }
}
public class Blah : IHaveAnId
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh : IHaveAnId
{
public int id {get;set;}
public string dohh { get; set; }
public string mahh { get; set; }
}
then you can do:
public List<IHaveAnId> TheList = new List<IHaveAnId>();
and in some method:
TheList.Add(new Blah{id=1,blahh = "someValue"});
TheList.Add(new Doh{id =2, dohh = "someValue", mahh = "someotherValue"});
to iterate through the list:
foreach(IHaveAnId item in TheList)
{
Console.WriteLine("TheList contains an item with id {0}", item.id);
//item.id is allowed since you access the property of the class over the interface
}
or to iterate through all Blahs:
foreach(Blah item in TheList.OfType<Blah>())
{
Console.WriteLine("TheList contains a Blah with id {0} and blahh ='{1}'", item.id, item.blahh);
}
Edit:
the 2 methods and a int field holding the autovalue:
private int autoValue = 0;
public void AddBlah(string blahh)
{
TheList.Add(new Blah{id = autovalue++, blahh = blahh});
}
public void AddDoh(string dohh, string mahh)
{
TheList.Add(new Doh{id = autovalue++, dohh = dohh, mahh = mahh});
}
Another Edit
public List<object> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result.Cast<object>().ToList();
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result.Cast<object>.ToList();
}
return null;
}
}
in the view you then have to decide what type it is. In asp.net MVC you can use a display template and use reflection to get a good design. But then i still don't know what technology you are using.
Yet another Edit
TestClass:
public class SomeClass
{
public string Property { get; set; }
}
Repository:
public static class Repository
{
public static List<object> Whatever(string prpClass)
{
switch (prpClass)
{
case "SomeClass":
return new List<SomeClass>()
{
new SomeClass{Property = "somestring"},
new SomeClass{Property = "someOtherString"}
}.Cast<object>().ToList();
default:
return null;
}
}
}
And a controller action in mvc:
public JsonResult Test(string className)
{
return Json(Repository.Whatever("SomeClass"),JsonRequestBehavior.AllowGet);
}
then i called it with: http://localhost:56619/Home/Test?className=SomeClass
And got the result:
[{"Property":"somestring"},{"Property":"someOtherString"}]
Is this what you are trying to do?
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
class Program
{
public static List<T> Whatever<T>(int count) where T: new()
{
return Enumerable.Range(0, count).Select((i) => new T()).ToList();
}
static void Main(string[] args)
{
var list=Whatever<Doh>(100);
// list containts 100 of "Doh"
}
}
In my controller I'm looping through items and saving them to my db. The problem is that it saves the first item, but none of the others. I put a breakpoint on the "SaveItem()" line in the loop and it hits it every time, but what seems odd to me is that it only goes through to the method for the 1st item.
What am I doing wrong?
public void SubmitItem(Cart cart, ShippingDetails shippingDetails, ProcessedItems processedItem, string orderID)
{
var cartItems = cart.Lines;
//CartIndexViewModel cartIndex = new CartIndexViewModel();
//var customID = cartIndex.OrderID;
foreach(var item in cartItems)
{
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
}
public class EFProcessedItemsRepository : IProcessedItems
{
private EFDbContext context = new EFDbContext();
public IQueryable<ProcessedItems> ProcessedItem
{
get { return context.ProcessedItems; }
}
public void SaveItem(ProcessedItems processedItem)
{
if(processedItem.ProcessedID == 0)
{
try
{
context.ProcessedItems.Add(processedItem);
context.SaveChanges();
}
catch (Exception)
{
throw;
}
}
else
{
context.Entry(processedItem).State = EntityState.Modified;
}
}
public void DeleteItem(ProcessedItems processedItem)
{
context.ProcessedItems.Remove(processedItem);
context.SaveChanges();
}
}
here is the class for the processedItem:
public class ProcessedItems
{
[Key]
public int ProcessedID { get; set; }
public string OrderID { get; set; }
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public string ImageName { get; set; }
public string Image2Name { get; set; }
public string Image3Name { get; set; }
public string Status { get; set; }
//shipping
public string BuyerName { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
}
Interface:
public interface IProcessedItems
{
IQueryable<ProcessedItems> ProcessedItem { get; }
void SaveItem(ProcessedItems processedItem);
void DeleteItem(ProcessedItems processedItem);
}
try calling context.SaveChanges() after adding all of the items, I think it should persist them all in one go.
Another thing to try:
Refactor your code so that SaveItem accepts only one item to save, Add it and call SaveChanges()
Loop through the cart items outside the method and call the method with one item to save at a time.
// set orderID, shippingDetails above
foreach(var item in cartItems)
{
ProcessedItems processedItem = new ProcessedItems();
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
SubmitItem(processedItem);
}
public void SubmitItem(ProcessedItems processedItem)
{
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
I think it is because processedItem is the same instance for each loop iteration. So after it has been through SaveItem once, it has its ProcessedID set and therefore won't get processed again.
My first guess is that you always store one entity, which is stored in processedItem, which is a input parameter. Try to create new Entity on each loop and then save it. In other words, you assign values to input parameter
processedItem.OrderID = orderID;
and then store same entity each time, but with changed fields
processedItems.SaveItem(processedItem);