I have created list. And it compiles and shows only one item. I need to make it show all my inserted items. For example I try insert one more. How should i do that?
namespace ConsoleApplication5
{
public class DocConfig
{
public string Description { get; set; }
public List<DocPart> Parts;
public class DocPart
{
public string Title { get; set; }
public string TexLine { get; set; }
public class Program
{
public static int Main()
{
List<DocPart> Parts = new List<DocPart>();
var doc = new DocConfig();
doc.Description = "bla bla";
doc.Parts = new List<DocPart>();
doc.Parts.Add(new DocPart { Title = "aaa", TexLine = #"\include{aaa.tex}" });
doc.Parts.Add(new DocPart { Title = "bbb ", TexLine = #"\include{bbb.tex}" });
foreach (DocPart part in doc.Parts)
{
Console.WriteLine(part.Title);
Console.ReadLine();
Console.ReadKey();
{
return 0;
}
}
return -1;
}
}
}
}
The reason it is only showing one is because your loop over parts is returning from the method and therefore it never gets chance to complete any other iterations.
The solution is to not return early (Remove the return 0;) from this method and instead let it run to the end.
Some other changes I made below were:
Removed the read keys from the for loop. You probably don't want the user to have to press a key every iteration either.
Un-nested classes. Your nested classes also seemed wierd to me and will just lead you to messy code.
namespace ConsoleApplication5
{
public class DocConfig
{
public string Description { get; set; }
public List<DocPart> Parts;
}
public class DocPart
{
public string Title { get; set; }
public string TexLine { get; set; }
}
public class Program
{
public static int Main()
{
List<DocPart> Parts = new List<DocPart>();
var doc = new DocConfig();
doc.Description = "bla bla";
doc.Parts = new List<DocPart>();
doc.Parts.Add(new DocPart { Title = "aaa", TexLine = #"\include{aaa.tex}" });
doc.Parts.Add(new DocPart { Title = "bbb ", TexLine = #"\include{bbb.tex}" });
foreach (DocPart part in doc.Parts)
{
Console.WriteLine(part.Title);
}
Console.ReadKey();
return -1;
}
}
}
Related
I have two lists. There are only one field difference. How to fill the lists with each other.
[Serializable()]
public class Lst1
{
public string filed1 { get; set; }
public Int16 filed2 { get; set; }
.
.
.
public Boolean filed100 { get; set; }
}
[Serializable()]
public class Lst2
{
public string filed1 { get; set; }
public Int16 filed2 { get; set; }
.
.
.
public Boolean filed100 { get; set; }
public string filed101 { get; set; }
}
List<Lst1> Lst1_ = new List<Lst1>();
List<Lst2> Lst2_ = new List<Lst2>();
I fill out lists from files.
then,I need to fill out the list two from list one,There are many fields And I do not want to use the foreach loop.
It should be remembered that my previous class was already built and serialized and stored in a file. And now I need to transfer the previous information to the second class structure.
I do not want to use this loop!
foreach (var t in Lst1_)
{
Lst2_.Add(new lst2
{
filed1 = t.filed1,
filed2 = t.filed2,
.
.
.
filed100 = t.filed100,
filed101 = "kk"
}
}
Is this what you want?
class Lst1
{
public string filed1 { get; set; }
public string filed2 { get; set; }
public string filed3 { get; set; }
public string filed4 { get; set; }
public string filed5 { get; set; }
}
class Lst2
{
public string filed1 { get; set; }
public string filed2 { get; set; }
public string filed3 { get; set; }
public string filed4 { get; set; }
public string filed5 { get; set; }
public string filed6 { get; set; }
}
void CopyData()
{
// test data
List<Lst1> Lst1_ = new List<Lst1>()
{
new Lst1()
{
filed1 = "1",
filed2 = "2",
filed3 = "3",
filed4 = "4",
filed5 = "5",
},
new Lst1()
{
filed1 = "6",
filed2 = "7",
filed3 = "8",
filed4 = "9",
filed5 = "10",
},
};
List<Lst2> Lst2_ = new List<Lst2>();
foreach (var item in Lst1_)
{
Type type1 = item.GetType();
PropertyInfo[] properties1 = type1.GetProperties();
var current = new Lst2();
Type type2 = current.GetType();
PropertyInfo[] properties2 = type2.GetProperties();
int k = 0;
foreach (PropertyInfo property in properties1)
{
var value = property.GetValue(item, null);
int n;
bool isNumeric = int.TryParse(value.ToString(), out n);
if (!isNumeric)
value = "Your desired value";
properties2[k].SetValue(current, value);
k++;
}
Lst2_.Add(current);
}
}
It copies everything from list 1 to list2.
No need to waste your time and money, AutoMapper can do it for you with only 2 lines of code:
using AutoMapper;
namespace ConsoleApp39
{
class Program
{
static void Main (string[] args)
{
// fill list1 with data
var list1 = new List1
{
Field1 = "test",
Field2 = 5,
Field3 = false,
};
// 1) configure auto mapper
Mapper.Initialize (cfg => cfg.CreateMap<List1, List2> ());
// 2) create list2 and fill with data from list1
List2 list2 = Mapper.Map<List2> (list1);
// fill extra fields
list2.Field4 = new byte[] { 1, 2, 3 };
}
}
public class List1
{
public string Field1 { get; set; }
public int Field2 { get; set; }
public bool Field3 { get; set; }
}
public class List2
{
public string Field1 { get; set; }
public int Field2 { get; set; }
public bool Field3 { get; set; }
public byte[] Field4 { get; set; } // extra field
}
}
Do Lst1 can inheritance from Lst2?
Something like this,
the two lists:
[Serializable()]
public class Lst1
{
public string filed1 { get; set; }
public int filed2 { get; set; }
public bool filed100 { get; set; }
}
[Serializable()]
public class Lst2 : Lst1
{
public string filed101 { get; set; }
}
and one print extension
public static class CExtensions
{
public static string PropertyList(this Lst1 obj)
{
var props = obj.GetType().GetProperties();
var sb = new StringBuilder();
foreach (var p in props)
{
sb.AppendLine(p.Name + ": " + p.GetValue(obj, null));
}
return sb.ToString();
}
}
then using it:
class Program
{
static void Main(string[] args)
{
const int I = 15;
try
{
//init first list
List<Lst1> Lst1_ = new List<Lst1>();
Init(Lst1_);
//print it
Console.WriteLine("Lst1_");
Console.WriteLine(new string('-', I));
Lst1_.ForEach(x => Console.WriteLine(x.PropertyList()));
Console.WriteLine(new string('=', I));
Console.ReadKey();
//init second list
List<Lst1> Lst2_ = Lst1_.Cast<Lst1>().ToList(); //equivalent of two next lines
//List<Lst1> Lst2_ = new List<Lst2>().ConvertAll(x => (Lst1)x);
//Lst2_.AddRange(Lst1_);
//add one more
Lst2_.Add(new Lst2
{
filed1 = "101",
filed2 = 202,
filed100 = true,
filed101 = "10100"
});
//and print
Console.WriteLine("Lst2_");
Console.WriteLine(new string('-', I));
Lst2_.ForEach(x => Console.WriteLine(x.PropertyList()));
Console.WriteLine(new string('=', I));
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
private static void Init(List<Lst1> lst_)
{
for (int i = 1; i <= 3; i++)
{
lst_.Add(new Lst1
{
filed1 = i.ToString(),
filed2 = 2 * i,
filed100 = i % 2 == 0
});
}
}
}
enjoy =)
Please check from Json output i wanted using JavaScriptSerializer. Then check class helper i created using json2csharp.com. Problem is in controller. I am not getting correct output as per my required Jason. I am doing correct in controller? Where the problem can be? Please ask question if you want to know something specific, sorry its hard to describe more clearly.
Helper Class Code:
public class ItemsFromFile
{
public string ASIN { get; set; }
public string Title { get; set; }
public List<Product> products { get; set; }
}
public class ItemsDeatails
{
public List<ItemsFromFile> ItemsFromFile { get; set; }
}
public class File
{
public string nameLocator { get; set; }
public ItemsDeatails itemsDeatails { get; set; }
}
public class RootObject
{
public string Token { get; set; }
public File file { get; set; }
}
Controller code:
if (type == "Salefreaks")
{
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var ItemsFromFile = new ItemsFromFile()
{
products = new List<Product>()
};
var ItemsDeatails = new ItemsDeatails()
{
};
var File = new File()
{
nameLocator = "testimport1"
};
var RootObject = new RootObject()
{
Token = token
};
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems)
{
ItemsFromFile.products.Add(new Product { ASIN = item.ASIN, Title = item.EbayTitle });
}
var json = new JavaScriptSerializer().Serialize(RootObject);
}
Required Json Output code:
{
"Token": "7f3099b0-36b1",
"file": {
"nameLocator": "testimport1",
"itemsDeatails": {
"ItemsFromFile": [
{
"ASIN": "B011KVFT9Y",
"Title": "Disney Batman Durable Party Beach Outdoor Adventure Camp Chair w/ Storage Bag"
},
{
"ASIN": "B01D4KRBW2",
"Title": "High Quality Diy Oil Painting Paint Number Kit Theme-Romantic Street A Frameless"
}
]
}
}
}
You can initialize internal objects in the code in the constructor as well.
public class RootObject
{
public string Token { get; set; }
public File file { get; set; }
}
public class File
{
public File()
{
this.itemsDeatails = new ItemsDeatails();
}
public string nameLocator { get; set; }
public ItemsDeatails itemsDeatails { get; set; }
}
public class ItemsDeatails
{
public ItemsDeatails(){
this.ItemsFromFile = new List<ItemsFromFile>();
}
public List<ItemsFromFile> ItemsFromFile { get; set; }
}
public class ItemsFromFile
{
public ItemsFromFile(){
this.products = new List<Product>();
}
public List<Product> products { get; set; }
}
public class Product {
public string ASIN { get; set; }
public string Title { get; set; }
}
Initialize your items properly. And create Root Object from the ground up.
Populate the internal classes first and then later ones.
var itemDetails = new ItemsDeatails();
itemDetails.ItemsFromFile = new ItemsFromFile();
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems)
{
itemDetails.ItemsFromFile.products.Add(new Product { ASIN = item.ASIN, Title = item.EbayTitle });
}
var fl = new File(){
nameLocator = "testimport1",
itemsDeatails = itemDetails
}
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var root = new RootObject()
{
Token = token,
file = fl
}
var json = new JavaScriptSerializer().Serialize(root);
Ensure that all your objects are assigned appropriately.
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var RootObject = new RootObject() {
Token = token,
file = new File() {
nameLocator = "testimport1",
itemsDeatails = new ItemsDeatails() {
ItemsFromFile = new List<ItemsFromFile>()
}
}
};
var itemsFromFile = new ItemsFromFile();
itemsFromFile.products = new List<Product>();
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems) {
itemsFromFile.products.Add(new Product { ASIN = item.ASIN, Title = item.EbayTitle });
}
RootObject.file.itemsDeatails.ItemsFromFile.Add(itemsFromFile);
var json = new JavaScriptSerializer().Serialize(RootObject);
That being said, it appears that you do not need the list of products inside of the ItemsFromFile class. This definition likely makes more sense:
public class ItemsFromFile {
public string ASIN { get; set; }
public string Title { get; set; }
}
Then your code would be something like this:
var token = ctx.BulkStores.FirstOrDefault(x => x.StoreName == store && x.Type == 1).Token;
var RootObject = new RootObject() {
Token = token,
file = new File() {
nameLocator = "testimport1",
itemsDeatails = new ItemsDeatails() {
ItemsFromFile = new List<ItemsFromFile>()
}
}
};
var singleItems = ctx.BulkScannedItems.Where(x => x.UserSellerScanRequestId == id).ToList();
foreach (var item in singleItems) {
RootObject.file.itemsDeatails.ItemsFromFile.Add(new ItemsFromFile { ASIN = item.ASIN, Title = item.EbayTitle });
}
So I have the json below that I want to Deseralize into Classes so I can work with it. But the issues is that the top two fields are a different type to all the rest
"items": {
"averageItemLevel": 718,
"averageItemLevelEquipped": 716,
"head": { ... },
"chest": { ... },
"feet": { ... },
"hands": { ... }
}
Where ... is a the Item class below, but the problem is that 2 of the fields are ints and the rest are Item, there are about 20 fields in total. So what I'd like to do is put them into a Dictionary<string, Item> but the 2 int fields are preventing me from Deseralizing it into that. I'm using JavaScriptSerializer.Deserialize<T>() to do this.
I could have each item as it's own class with the name of the item as the name of the class, but I find that to be very bad, repeating so much each time, also very hard to work with later since I cant iterate over the fields, where as I could a Dictionary. Any idea how I could overcome this?
public class Item
{
public ItemDetails itemDetails { get; set; }
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public TooltipParams tooltipParams { get; set; }
public List<Stat> stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public List<int> bonusLists { get; set; }
}
Update: from the comments I came up with this solution
JObject jsonObject = JObject.Parse(json);
jsonObject["averageItemLevel"] = int.Parse(jsonObject["items"]["averageItemLevel"].ToString());
jsonObject["averageItemLevelEquipped"] = int.Parse(jsonObject["items"]["averageItemLevelEquipped"].ToString());
jsonObject["items"]["averageItemLevel"].Parent.Remove();
jsonObject["items"]["averageItemLevelEquipped"].Parent.Remove();
var finalJson = jsonObject.ToString(Newtonsoft.Json.Formatting.None);
var character = _serializer.Deserialize<Character>(finalJson);
character.progression.raids.RemoveAll(x => x.name != "My House");
return character
If I add these two classes to match your JSON I can serialize and deserialize the objects:
public class root
{
public Items items { get; set; }
}
public class Items
{
public int averageItemLevel { get; set; }
public int averageItemLevelEquipped { get; set; }
public Item head {get;set;}
public Item chest {get;set;}
public Item feet {get;set;}
public Item hands {get;set;}
}
Test rig with the WCF Serializer:
var obj = new root();
obj.items = new Items
{
averageItemLevel = 42,
feet = new Item { armor = 4242 },
chest = new Item { name = "super chest" }
};
var ser = new DataContractJsonSerializer(typeof(root));
using (var ms = new MemoryStream())
{
ser.WriteObject(ms, obj);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
Console.WriteLine("and deserialize");
ms.Position = 0;
var deserializeObject = (root) ser.ReadObject(ms);
Console.WriteLine(deserializeObject.items.feet.armor);
}
And with the JavaScriptSerializer:
var jsser = new JavaScriptSerializer();
var json = jsser.Serialize(obj);
Console.WriteLine(json);
Console.WriteLine("and deserialize");
var djson = jsser.Deserialize<root>(json);
Console.WriteLine(djson.items.feet.armor);
Both serializers give the same result for your given JSON.
I am adding 2items to my list and I want to look at them in console. But something went wrong, maybe you can help? I think main problem is in foreach loop. Where it says Part can not be found.
class Program
{
static void Main(string[] args)
{
public class DocPart
{
public string Title { get; set; }
public string TexLine { get; set; }
}
public class DocConfig
{
public string Description { get; set; }
public List<DocPart> Parts { get; set; }
DocConfig()
{
var doc = new DocConfig();
doc.Description = "bla bla";
doc.Parts.Add(new DocPart { Title = "aaa", TexLine = #"\include{aaa.tex}" });
doc.Parts.Add(new DocPart { Title = "bbb", TexLine = #"\include{bbb.tex}" });
this.Parts = new List<DocPart>();
foreach (DocPart part in doc.Parts)
{
Console.WriteLine(part.Title);
Console.ReadLine();
}
}
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
var config = (DocConfig)serializer.ReadObject(ms);
return config;
}
public string SaveToString()
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream();
serializer.WriteObject(ms, this);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
Can't you just use linq string.Join(",", my list)?
I have 2classes and I want to add a list to it. I will use check boxes to fill in my list. But for now how I should create list?
public class DocPart
{
public string Title { get; set; }
public string TexLine { get; set; }
}
public class DocConfig
{
public string Description { get; set; }
public List<DocPart> Parts { get; set; }
public static DocConfig LoadFromString(string jsonData)
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
var config = (DocConfig)serializer.ReadObject(ms);
return config;
}
public string SaveToString()
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream();
serializer.WriteObject(ms, this);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
I want to create list for example at start for 2 items. I am thinking of this code:
var doc = new DocConfig();
doc.Description = "bla bla";
doc.Parts = new List<DocPart>();
doc.Parts.Add(new DocPart { Title = "aaa", TexLine = #"\include{aaa.tex}"});
doc.Parts.Add(new DocPart { Title = "bbb", TexLine = #"\include{bbb.tex}" });
how should I do this?
EDIT:
Also how can I display list records in console application?
EDIT:
Maybe I did mistakes in my code:
public class DocConfig
{
public string Description { get; set; }
public List<DocPart> Parts { get; set; }
DocConfig()
{
var doc = new DocConfig();
doc.Description = "bla bla";
doc.Parts.Add(new DocPart { Title = "aaa", TexLine = #"\include{aaa.tex}" });
doc.Parts.Add(new DocPart { Title = "bbb", TexLine = #"\include{bbb.tex}" });
this.Parts = new List<DocPart>()
foreach (Part part in doc.Parts)
{
Console.WriteLine(part.Title);
}
}
add to your DocConfig class this:
DocConfig()
{
this.Parts= new List<DocPart>();
}
and remove
doc.Parts = new List<DocPart>();
also read about constructors, rest of your coud is fine.
EDIT:
to check your list in console you can use foreach loop that is best option to use with List:
foreach (var part in doc.Parts)
{
Console.WriteLine(part.Title);
}