I have some problem here. Here it is:
I have this class
public class NewsFeedResources
{
public string Name { get; set; }
public string Id { get; set; }
public string Message { get; set; }
public static ObservableCollection<NewsFeedResources> _newsfeed = new ObservableCollection<NewsFeedResources>
{
new NewsFeedResources { Name = "Joe", Id = "1", Message="Foo" },
new NewsFeedResources { Name = "Wandy", Id = "2", Message="Bar" },
new NewsFeedResources { Name = "Yuliana", Id = "3", Message="Baz" },
new NewsFeedResources { Name = "Hardi", Id = "4", Message="Baz" },
};
public static ObservableCollection<NewsFeedResources> newsFeedResources
{ get { return _newsfeed; }
}
}
If I have another data such as
Name=John, Id=5, Message="Stack overflow"
Name=Jane, Id=6, Message="Hello world"
How can I add the data into the class, but not from the constructor? Thanks for the help
ObservableCollection exposes the Collection<T>.Add Method:
Adds an object to the end of the Collection.
So you'd have:
_newsfeed.Add(new NewsFeedResources {Name = "John",
Id = 5,
Message = "Stack overflow"});
_newsfeed.Add(new NewsFeedResources {Name = "Jane",
Id = 6,
Message = "Hello world"});
(typed from memory)
call a function from constructor or anywhere as u like and add items like below
NewsFeedResources NFR=new NewsFeedResources(){Name=John, Id=5, Message="Stack overflow"};
_newsfeed.add(NFR);
NewsFeedResources NFR1 =new NewsFeedResources(){Name=Jane, Id=6, Message="Hello world"};
_newsfeed.add(NFR);
Related
Could someone helpe me?
How can I code 'Shippings' class as an Array to get the json example below?
{
"seller_id": "123",
"amount": 100,
"order": {
"order_id": "1111",
"sales_tax": 0,
"product_type": "service"
},
"shippings": [{
"first_name": "John",
"phone_number": "5551999887766",
"shipping_amount": 3000,
"address": {
"street": "Street 35 Conts",
"number": "1000",
"complement": "ap1",
"postal_code": "90230060"
}
}],
"credit": {
"delayed": false,
"authenticated": false
}
}
I am doing this below, using asp.net mvc, but don't know how to get Shippings as Array [].
Can someone give me some exemplo or anything else... I'll appreciate.
var request = new GetNetRoot() {
SellerId = seller_id,
Amount = orderItens.Amount
Order = new GetNetPagOrder() {
OrderId = order.id.ToString(),
SalesTax = orderItens.Tax,
ProductType = orderItens.ProdType
},
Shippings = new GetNetPagShippings() {
FirstName = "",
PhoneNumber = usr.PhoneNumber,
ShippingAmount = orderItens.AmountShip,
Address = new GetNetPagAddress() {
Street = catEnd.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome,
Number = catEnd.NumEndereco,
Complement = catEnd.Complemento,
PostalCode = catEnd.IdEnderecoLogradouroNavigation.Cep
}
},
Credit = new GetNetPagCredit() {
Delayed = false,
Authenticated = false
}
};
var requestBody = JsonConvert.SerializeObject(request)
You should initialize Shippings like an array:
Shippings = new[] {
new GetNetPagShippings()
{
FirstName = "",
PhoneNumber = usr.PhoneNumber,
ShippingAmount = orderItens.AmountShip,
Address = new GetNetPagAddress()
{
Street = catEnd.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome,
Number = catEnd.NumEndereco,
Complement = catEnd.Complemento,
PostalCode = catEnd.IdEnderecoLogradouroNavigation.Cep
}
}
public class GetNetPagamentoRoot
{
...
public GetNetPagShippings[] Shippings { get; set; }
}
You can use array initializer syntax. Simplistic example would be array of int:
int[] myArray = new [] { 1, 2, 3 }
In your code Shippings should be initialized as an array.
var request = new GetNetRoot()
{
SellerId = seller_id,
Amount = orderItens.Amount
Order = new GetNetPagOrder()
{
OrderId = order.id.ToString(),
SalesTax = orderItens.Tax,
ProductType = orderItens.ProdType
},
// Array initializer with 2 elements.
Shippings = new[] {
new GetNetPagShippings()
{
FirstName = "",
PhoneNumber = usr.PhoneNumber,
ShippingAmount = orderItens.AmountShip,
Address = new GetNetPagAddress()
{
Street = catEnd.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome,
Number = catEnd.NumEndereco,
Complement = catEnd.Complemento,
PostalCode = catEnd.IdEnderecoLogradouroNavigation.Cep
}
},
new GetNetPagShippings()
{
FirstName = "",
PhoneNumber = usr.PhoneNumber,
ShippingAmount = orderItens.AmountShip,
Address = new GetNetPagAddress()
{
Street = catEnd.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome,
Number = catEnd.NumEndereco,
Complement = catEnd.Complemento,
PostalCode = catEnd.IdEnderecoLogradouroNavigation.Cep
}
}
},
Credit = new GetNetPagCredit()
{
Delayed = false,
Authenticated = false
}
};
var requestBody = JsonConvert.SerializeObject(request);
Your GetNetRoot outer class needs to define the "Shippings" property as a list or array of the GetNetPagShippings class as opposed to a single instance. When you serialize it to JSON, it will be represented as a JSON array of the object.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var myClassInstance = new MyOuterClass()
{
OuterProperty = "Outer Property",
MyInnerClassList = new List<MyInnerClass>()
{
new MyInnerClass()
{
InnerProperty = "Inner Property Item 1"
},
new MyInnerClass()
{
InnerProperty = "Inner Property Item 2"
}
}
};
string json = JsonConvert.SerializeObject(myClassInstance);
Console.WriteLine(json);
}
}
public class MyOuterClass
{
public string OuterProperty { get; set; }
public List<MyInnerClass> MyInnerClassList { get; set; }
}
public class MyInnerClass
{
public string InnerProperty { get; set; }
}
}
I have a data definition
I Deserialize JSON to this object
#return is JSON
JsonConvert.DeserializeObject<List<Dictionary<Object, Object>>>(utils.RemoveJsonOuterClass("GetTable", JsonConvert.DeserializeObject(#return).ToString()));
olist = [
[{
"item": 1
"Name "One"
}],
[{
"item": 2
"Name "Two"
}],
[{
"item": 1
"Name "One Two"
}]
];
This is a List<Dictionary<Object, Object>>
I need to find all of the items where "item" == 1.
Can I Use Linq? or is there any other way while using a large amount of data?
First: Your json is not correct fix that.
A colon should be present between Name and value.
A comma should be present after item value
and then change your code as below
//Create a class matching response object
public class ResponseItem
{
[JsonProperty("item")]
public int Item { get; set; }
public string Name { get; set; }
}
var responseJson = utils.RemoveJsonOuterClass("GetTable",
JsonConvert.DeserializeObject(#return).ToString();
var responseData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<List<ResponseItem, ResponseItem>>>(responseJson);
Then use foreach with Where and apply condition
foreach (var responseObject in responseData.Where(x=>x.First().Item.Equals(1)))
{
}
Where is deferred execution and on each loop, it returns an object.
Here is the screenshot of my local execution.
Don't know if u're right with the object type. But the task is easy to solve:
static void Main(string[] args)
{
// Build the object
List<Dictionary<int, TestObject>> list = new List<Dictionary<int, TestObject>>();
// fill it with dictionaries
list.Add(new List<TestObject>()
{
new TestObject(){ Id = 1, Name = "One" },
new TestObject() { Id = 2, Name = "Two" },
new TestObject() { Id = 3, Name = "Three" }
}.ToDictionary(d => d.Id));
list.Add(new List<TestObject>()
{
new TestObject() { Id = 2, Name = "Two" },
new TestObject() { Id = 3, Name = "Three" }
}.ToDictionary(d => d.Id));
list.Add(new List<TestObject>()
{
new TestObject(){ Id = 1, Name = "One" },
new TestObject() { Id = 2, Name = "Two" }
}.ToDictionary(d => d.Id));
// Let's build a single list to work with
IEnumerable<TestObject> completeList = list.SelectMany(s => s.Values);
// aaaand filter it
IEnumerable<TestObject> filteredList = completeList.Where(l => l.Id == 1);
}
public class TestObject
{
public int Id { get; set; }
public string Name { get; set; }
}
Most part is initialization ;-)
Hej hej,
i'm currently working on a c# wpf project where i want to dynamically populate a TreeView from a linear list of Items.
My starting point was this article on codeproject:
https://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode
John Smith shows how to use the HierarchalDataTemplate withing TreeViews. So far this is working. My problem is to dynamically generate a hierarchical Tree from a linear list of items. I have tried to adapt the solutions found here
Mapping a flat list to a hierarchical list with parent IDs C#
and here
TreeView directories in C# WPF
but somehow i did not succeed.
My item class looks like this:
public class Item
{
public string Name { get; set; }
public ItemPath[] ParentPath { get; set; }
public ItemPath[] Path { get; set; }
}
ItemPath class
public class ItemPath
{
public int Level { get; set; }
public string Name { get; set; }
}
Targeted hierarchial class
public class ItemTree
{
public string Name { get; set; }
public Item Item { get; set; }
public List<ItemTree> ChildTree { get; set; }
}
I am using this flat list to test my methods:
var items = new List<Item>()
{
new Item()
{
Name = "item 0",
Path = new ItemPath[]
{
new ItemPath() { Name = "Red", Level = 1 },
}
},
new Item()
{
Name = "item 1",
Path = new ItemPath[]
{
new ItemPath() { Name = "Red", Level = 1 },
new ItemPath() { Name = "Green", Level = 2 },
}
},
new Item()
{
Name = "item 2",
Path = new ItemPath[]
{
new ItemPath() { Name = "Red", Level = 1 },
new ItemPath() { Name = "Violet", Level = 2 },
}
},
new Item()
{
Name = "item 3",
Path = new ItemPath[]
{
new ItemPath() { Name = "Blue", Level = 1 },
new ItemPath() { Name = "Black", Level = 2 },
}
},
new Item()
{
Name = "item 4",
Path = new ItemPath[]
{
new ItemPath() { Name = "Blue", Level = 1 },
new ItemPath() { Name = "Green", Level = 2 },
}
},
new Item()
{
Name = "item 5",
Path = new ItemPath[]
{
new ItemPath() { Name = "Red", Level = 1 },
new ItemPath() { Name = "Green", Level = 2 },
}
},
};
My goal is to have a hierarchy like this
[Red]
item 0
[Green]
item 1
item 5
[Violet]
item 2
[Blue]
[Black]
item 2
[Green]
item 4
My current attempt is below. It's the rewritten version of the stackoverflow post from above:
// class to create dummy data as described above
var dummyData = new DummyData();
var items = dummyData.CreateTier2DummyList();
var cat = items.Select(r => new ItemTree()
{
Path = r.Path,
Item = r,
// parent path is generated dynamically
ParentPath = r.Path.Reverse().Skip(1).Reverse().ToArray(),
}).ToList();
var lookup = cat.ToLookup(c => c.ParentPath);
foreach (var c in cat)
{
if (lookup.Contains(c.Path))
c.ChildTree = lookup[c.ParentPath].ToList();
}
Somehow i think that using an array as the path and parent path is not a good idea. But it reflects an absolute path (comparable to a file path in a file system).
Currently doing some homework on C# basics. I'm getting a null pointer on this line and can't figure out what's caussing it.:
List<Project> projecten = new List<Project>{
new Project {
name = "project a",
deelnemers =
{
new Person { name = "Ed" },
new Person { name = "Mike" },
}
},
new Project {
name = "project b",
deelnemers = {
new Person {name = "Max" },
new Person {name = "Peter" },
}
}
};
the person and project classes are defined correctly I think:
public class Project
{
public string name { get; set; }
public List<Person> deelnemers {get; set;}
}
public class Person
{
public string name { set; get; }
}
It's probably something stupid but I don't see it.
The complete file is this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
// Maak een collection mbv initializers van minimaal 3 projecten met meerdere projectleden
List<Project> projecten = new List<Project>{
new Project {
name = "project a",
deelnemers =
{
new Person { name = "Xanvier" },
new Person { name = "Jantje" },
}
},
new Project {
name = "project b",
deelnemers = {
new Person {name = "Pietje" },
new Person {name = "Keesje" },
}
}
};
List<Int16> p = new List<Int16> { 1,2,3 };
//var projectje = new Project{ name = "project a" };
}
}
public class Project
{
public string name { get; set; }
public List<Person> deelnemers {get; set;}
}
public class Person
{
public string name { get; set; }
}
}
This part is a collection initializer:
deelnemers =
{
new Person { name = "Ed" },
new Person { name = "Mike" },
}
This is perhaps one of the most confusing forms of syntax in C#. It does not initialize your list. It only calls Add on it.
You need to initialize the List as well:
deelnemers = new List<Person> {
new Person { name = "Xanvier"},
//
}
Or, you can initialize the List in the constructor of Project. That way, your original code will work as expected.
The solution is, like Dennis_E said in a comment:
deelnemers = { new Person ... } will compile. The problem is, it does not initialize your list. It will only call Add. You need to say:
deelnemers = new List<Person> { ...
So the problem was that I forgot to initialize the list.
try this
List projecten = new List{
new Project {
name = "projecta",
deelnemers = new List{
{new Person { name = "Ed" }},
{new Person { name = "Mike" }}
}
},
new Project {
name = "projectb",
deelnemers = new List<Person>{
{new Person {name = "Max" }},
{new Person {name = "Peter" }}
}
}
};
I have a class and want to add some data on construction so i can used it without using database like :
public partial class ActionTypeList
{
public ActionTypeList()
{
new ActionTypeList { Id= "2", FName= "hanumanji" };
new ActionTypeList { Id= "4", FName= "temples" };
new ActionTypeList { Id= "38", FName= "books" };
new ActionTypeList { Id= "28", FName= "stories" };
}
public string Id{ get; set; }
public string FName{ get; set; }
}
I just given an example, how to do it I don't know.
If you need some data to work with then you will want to create separate instances outside the class not in it, that is a bad practice. If you truly feel that you must have data in this class then add a static method to get some your default stuff.
public partial class ActionType
{
public string Id { get; set; }
public string FName { get; set; }
public static IEnumerable<ActionType> GetDefaultActionTypes() {
return new List<ActionType> {
new ActionType { Id = "2", FName = "hanumanji" },
new ActionType { Id = "4", FName = "temples" },
new ActionType { Id = "28", FName = "books" },
new ActionType { Id = "38", FName = "stories" },
};
}
}
You can then use the static method like this
var myDefaultActionTypes = ActionType.GetDefaultActionTypes();
Create a new class ActionType and store your items in the ActionTypeList:
public class ActionType {
public ActionType() {
}
public string Id { get; set; }
public string FName { get; set; }
}
public class ActionTypeList : List<ActionType> {
public ActionTypeList() {
Add(new ActionType() { Id = "2", FName = "hanumanji" });
Add(new ActionType { Id = "4", FName = "temples" });
Add(new ActionType { Id = "38", FName = "books" });
Add(new ActionType { Id = "28", FName = "stories" });
}
}
You can define a static method inside of your class
public static List<ActionTypeList> GetActionTypes()
{
return new List<ActionTypeList>
{
new ActionTypeList { Id= "2", FName= "hanumanji" };
new ActionTypeList { Id= "4", FName= "temples" };
new ActionTypeList { Id= "38", FName= "books" };
new ActionTypeList { Id= "28", FName= "stories" };
}
}
And whenever you want to get your sample list you can call this method.
var list = ActionTypeList.GetActionTypes();