C# initializer null pointer - c#

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" }}
}
}
};

Related

How does serialize a list of objects in xml work?

I want to serialize my list of objects into a xml file with an path and deserialize it again.
I have a simple class of object with two strings:
public partial class Form1 : Form
{
[Serializable]
public class My_obj
{
public string Name { get; set; }
public string Score { get; set; }
}
And i have a list of this objects:
public List<My_obj> Score_Liste = new List<My_obj>()
{
new My_obj() { Name = "John Doe", Score = "one" },
new My_obj() { Name = "Jane Doe", Score = "two" },
new My_obj() { Name = "Joe Doe", Score = "three" },
new My_obj() { Name = "Janna Doe", Score = "four" },
new My_obj() { Name = "Jonathan Doe", Score = "five"}
}; //List
}
I tried something with Filestream and BinaryFormatter.
Can someone show me, what did i have to do.
Thank you.
Here's an example using the XmlSerializer in conjuction with File.Open
using System.Xml.Serialization;
var serializer = new XmlSerializer(typeof(List<My_obj>));
Serialization:
using (var stream = File.OpenWrite(xmlFilePath))
{
serializer.Serialize(stream, Score_Liste);
}
Deserialization:
using (var stream = File.OpenRead(xmlFilePath))
{
var list = (List<My_obj>)serializer.Deserialize(stream);
}

How to sort a list of objects by another list

I have two classes:
class Location
{
public string Address { get; set; }
}
class Person
{
public string Address { get; set; }
public string Name { get; set; }
}
And then I create two lists of objects:
var locations = new List<Location>()
{
new Location()
{
Address = "AA"
},
new Location()
{
Address = "BB"
},
new Location()
{
Address = "CC"
},
new Location()
{
Address = "BB"
}
};
var people = new List<Person>()
{
new Person()
{
Address = "BB",
Name = "Foo"
},
new Person()
{
Address = "CC",
Name = "Bar"
},
new Person()
{
Address = "AA",
Name = "xxx"
},
new Person()
{
Address = "BB",
Name = "yyy"
},
};
What I want is to sort the people list by matching Address property in the locations list. This is the result I would like to have:
xxx
Foo
Bar
yyy
I tried with this code:
var orderedPeopleList = people.OrderBy(p => locations.FindIndex(l => l.Address.Equals(p.Address)));
But it is not working correctly and the two last lines are in the wrong order. What is the best way to do this ordering with linq?
var orderedPeopleList = new List<Person>();
foreach (var location in locations)
{
var foundPeople = people.Where(p => p.Address == location.Address).FirstOrDefault();
if (foundPeople != null)
{
orderedPeopleList.Add(foundPeople);
people.Remove(foundPeople);
}
}
just do it :
locations= locations.OrderBy(x => x.Address).ToList();
var orderedPeopleList=new List<Person>();
for (var i = 0; i < locations.Count(); i++)
{
peopelOrderedList.Add(people.FirstOrDefault(x => x.Address == locations[i].Address && peopelOrderedList.All(c => c.Name != x.Name)));
}
peopelOrderedList.RemoveAll(x => x == null);

C# converting a list to a hierarchy

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).

How do I initialize this anonymous function?

var groups = new List<Group>
{
new Group{
Name = "Train",
Members = new List<Colleague>{
{FirstName = "Thomas", LastName = "Tank"},
{FirstName = "Honey", LastName = "Booboo"}
}
},
new Group{Name = "Bus"}
};
I am getting a red underline under 'FirstName' and 'LastName'... meaning that I've initialised it wrong...
How can I initialise that (Colleague) List? I think I am incorrectly initialising that list (Members)...
Edit: To make things clearer,
public class Group
{
public string Name { get; set; }
public List<Colleague> Members { get; set; }
}
Edit: Following up discussion with Kirk Woll:
This is what I did with your advice. Members is null though...
var groups = new List<Group>
{
new Group
{
Name = "Train",
Members = new List<Colleague>{
new Colleague { FirstName = "Thomas", LastName = "Tank" },
new Colleague { FirstName = "Jet", LastName = "Starr" }
}
},
new Group{Name = "Bus"}
};
To summarise, there's a breakpoint after the initialisation of groups. Each Group (x2) has Name defined, but Members = null in the first Group ('Train'). Members must be initialised! Cheers.
You want:
Members = new List<Colleague>
{
new Colleague { FirstName = "Thomas", LastName = "Tank" },
new Colleague { FirstName = "Honey", LastName = "Booboo" }
}
Since it's a list of Colleague to which you're trying to add it.

Adding data to ObservableCollection in WPF

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);

Categories