Adding items to ObservableColletion - UWP C# - c#

When I'm trying to add items to observable collection, it always replace all items with items added last. What is the reason for it? My code is here
public class FavoriteClassList
{
public int ID { get; set; }
public string Name { get; set; }
}
public static ObservableCollection<FavoriteClassList> _FavoriteClassList = new ObservableCollection<FavoriteClassList>();
FavoriteClassList objFavoriteClassList = new FavoriteClassList();
for (int m=1;m<=10;m++)
{
objFavoriteClassList.ID = m;
objFavoriteClassList.Name = "Name"+m;
_FavoriteClassList.Add(objFavoriteClassList);
}
Now when printing values of AppGlobals._FavoriteClassList it shows 10 items. But ID and Name of each items is always 10 and Name10 respectively.

You added one object 10 times and rewrite it 10 times. Here is a fixed version:
public class FavoriteClassList
{
public int ID { get; set; }
public string Name { get; set; }
}
public static ObservableCollection<FavoriteClassList> _FavoriteClassList = new ObservableCollection<FavoriteClassList>();
for (int m=1;m<=10;m++)
{
FavoriteClassList objFavoriteClassList = new FavoriteClassList();
objFavoriteClassList.ID = m;
objFavoriteClassList.Name = "Name"+m;
_FavoriteClassList.Add(objFavoriteClassList);
}

Related

C# linq / Lambda - Adding an item to a list that summarizes all the items in the list

I have al list of Purches items
I want to add new item to my list, that sum all the items in my list
this is my code:
public class Purches
{
public int Id { get; set; }
public int Items { get; set; }
public int TotalPrice { get; set; }
}
List<Purches> purchesList = new List<Purches>() {
new Purches() {
Id = 1,
Items = 3,
TotalPrice = 220
},
new Purches() {
Id = 2,
Items = 5,
TotalPrice = 300
}
};
now, I want to add the list new item that sum the Items and the TotalPrice properties
the result will be something like that:
List<Purches> purchesList = new List<Purches>() {
new Purches() {
Id = 1,
Items = 3,
TotalPrice = 220
},
new Purches()
{
Id = 2,
Items = 5,
TotalPrice = 300
},
new Purches()
{
Id = 0,
Items = 8,
TotalPrice = 550
}
};
I have to do it via linq / Lambda in c#
I would not recommend adding a summary item of the same type. That is just likely to lead to confusion. A better solution would be to to use either a separate object for the total, or use different types with a shared interface, for example:
public class PurchaceSummary{
public List<Purches> Purchases {get;}
public TotalItemCount => Items.Sum(p => p.Items);
public TotalPrice => Items.Sum(p => p.TotalPrices);
}
Or
public interface IPurchaseLineItem{
public int Items { get; }
public int TotalPrice { get; }
}
public interface Purchase : IPurchaseLineItem{
public int Id { get; set; }
public int Items { get; set; }
public int TotalPrice { get; set; }
}
public interface PurchaseSummary : IPurchaseLineItem{
public int Items { get; set; }
public int TotalPrice { get; set; }
}
// Use the LINQ methods from the previous example to create your totals for the summary
In either case it should be immediately obvious for everyone what each value represents.
Purches totalSum = new Purches
{
Id = 0,
Items = purchesList.Sum(p => p.Items),
TotalPrices = purchesList.Sum(p => p.TotalPrices)
};
// now add it to your list if desired

cant figure out how to map this json into C# classes

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.

How retrieve value from string collections in c#

I have a collection defined by:
public class CompanyModel
{
public string compnName { get; set; }
public string compnAddress { get; set; }
public string compnKeyProcesses { get; set; }
public string compnStandards { get; set; }
}
Then I stored names and addresses to this collection from a data table:
List<CompanyModel> companies = new List<CompanyModel>();
for(int i = 0; i < dt.Rows.Count; i++)
{
companies.Add(new CompanyModel
{
compnName = dt.Rows[i]["companyName"].ToString(),
compnAddress = dt.Rows[i]["address"].ToString()
});
}
My question is how could I retrieve each compnName from that collection ?
I tried this
foreach (CompanyModel company in companies)
{
string compnyName = company.compnName;
But it return me blank result.
The simplest option would be to use LINQ, e.g.
var names = companies.Select(c => c.compnName);

RavenDB query with Linq and enum

Given this document class:
public class Tea
{
public String Id { get; set; }
public String Name { get; set; }
public TeaType Type { get; set; }
public Double WaterTemp { get; set; }
public Int32 SleepTime { get; set; }
}
public enum TeaType
{
Black,
Green,
Yellow,
Oolong
}
I store a new Tea with the following code:
using (var ds = new DocumentStore { Url = "http://localhost:8080/" }.Initialize())
using (var session = ds.OpenSession("RavenDBFirstSteps"))
{
Tea tea = new Tea() { Name = "Earl Grey", Type = TeaType.Black, WaterTemp = 99d, SleepTime = 3 };
session.Store(tea);
session.SaveChanges();
Console.WriteLine(tea.Id);
}
The tea will be successfully saved, but when I try to query all black teas with linq, I am getting no results:
using (var ds = new DocumentStore { Url = "http://localhost:8080/" }.Initialize())
using (var session = ds.OpenSession("RavenDBFirstSteps"))
{
var dbTeas = from teas in session.Query<Tea>()
where teas.Type == TeaType.Black
select teas;
foreach (var dbTea in dbTeas)
{
Console.WriteLine(dbTea.Id + ": " + dbTea.Name);
}
}
I also tried to save the Enum as Integer with the following command:
ds.Conventions.SaveEnumsAsIntegers = true;
But, the result is the same. All works when I use the Name or the WaterTemp. Does RavenDB supports Enums in this way or I am totally wrong?
It seemed that I got the answer. It is always not recommended to use properties with a name like Type, which can be a reserved keyword.
I renamed Type and everything works, so the answer is:
public class Tea
{
public String Id { get; set; }
public String Name { get; set; }
public TeaType TeaType { get; set; }
public Double WaterTemp { get; set; }
public Int32 SleepTime { get; set; }
}

Add an ObservableCollection within a ObservableCollection

I need to add a ObservableCollection ObservableCollection within another, is it possible?
Items = new ObservableCollection<WidgetCollectionItem>();
foreach (XElement wid in document.Root.Elements("widget"))
{
WidgetCollectionItem item = new WidgetCollectionItem();
item.nombreWidget = wid.Attribute("caption").Value;
foreach (XElement service in wid.Elements("service"))
{
item.nombreServicio = service.Attribute("caption").Value;
item.valor = service.Element("xvalue").Value;
item.color = service.Element("xcolor").Value;
item.alerta = service.Element("xalert") != null ? service.Element("xalert").Value : null;
Items.Add(item);
}
}
The problem is that each (item.nombreWidget) contains more than one (item.nombreServicio). And I need a ObservableCollection of services within an ObservableCollection of nombreWidget
Yes, you can.
new ObservableCollection<ObservableCollection<WidgetCollectionItem>>()
so you can do something like this:
Items = new ObservableCollection<ObservableCollection<WidgetCollectionItem>>();
foreach (XElement wid in document.Root.Elements("widget"))
{
ObservableCollection<WidgetCollectionItem> services = new ObservableCollection<WidgetCollectionItem>();
foreach (XElement service in wid.Elements("service"))
{
WidgetCollectionItem widget = new WidgetCollectionItem();
widget.nombreWidget = wid.Attribute("caption").Value;
widget.nombreServicio = service.Attribute("caption").Value;
widget.valor = service.Element("xvalue").Value;
widget.color = service.Element("xcolor").Value;
widget.alerta = service.Element("xalert") != null ? service.Element("xalert").Value : null;
services.Add(widget);
}
Items.Add(services)
}
Good idea kindasimple, but still can not show what I want. I grab a xml data, and these want them displayed in a grid
The end result would be this:
nombreWidget1
nombreServicio1
nombreWidget2
nombreServicio2
nombreServicio2
nombreServicio2
If nombreWidget has only one service is fine, but if you have more than one nombreWidget nombreServicio, I can not show well on screen
I need the ObservableCollection
public class WidgetCollectionItem
{
public string nombreWidget { get; set; }
}
Contains an ObservableCollection
public class WidgetServiciosCollectionItem
{
public string nombreServicio { get; set; }
public string valor { get; set; }
public string color { get; set; }
public string alerta { get; set; }
}
Looks like I got what I wanted to achieve, but still does not show me all the data in the grid:
Solution to earlier:
Items = new ObservableCollection<WidgetCollectionItem>();
foreach (XElement wid in document.Root.Elements("widget"))
{
WidgetCollectionItem widget = new WidgetCollectionItem();
widget.nombreWidget = wid.Attribute("caption").Value;
foreach (XElement service in wid.Elements("service"))
{
ServiciosWidgetCollectionItem ser = new ServiciosWidgetCollectionItem();
widget.ItemsSer = new ObservableCollection<ServiciosWidgetCollectionItem>();
ser.nombreServicio = service.Attribute("caption").Value;
ser.valor = service.Element("xvalue").Value;
ser.color = service.Element("xcolor").Value;
ser.alerta = service.Element("xalert") != null ? service.Element("xalert").Value : null;
widget.ItemsSer.Add(ser);
}
Items.Add(widget);
}
public class WidgetCollectionItem
{
public string nombreWidget { get; set; }
public ObservableCollection<ServiciosWidgetCollectionItem> ItemsSer { get; set; }
}
public class ServiciosWidgetCollectionItem
{
public string nombreServicio { get; set; }
public string valor { get; set; }
public string color { get; set; }
public string alerta { get; set; }
}
How do I go also in the data grid ObservableCollection?

Categories

Resources