I have some object with different properties. And i want to store to List using List<dynamic> and i already did.
But i have some problem when try to find specific object what I need.
For example:
I have 2 object Movie and Genre
Movie Object
Movie movie = new Movie()
{
Title = Title,
Description = Description
};
Genre Object
Genre genre = new Genre ()
{
Name = Name
};
And i store like this :
List<dynamic> dynamics = new List<dynamic>();
dynamics.Add(movie);
dynamics.Add(genre);
I dont know to check the list is a movie or genre
I dont want use like dynamics[0] for get Movie object. because i have a lot more object than code below.
I try to use LINQ but did work or i miss something
Best solution is splitting to two collections. If you can not split you can do it in runtime every time dynamics.Where(x=>x.GetType() == typeof(Movie)).Cast<Movie>()
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 months ago.
Improve this question
I hope everyone is well.
I have some practice code here that I've been working on and the code works and I have no issues with it however, I don't find that I fully understand what I've written and why it works.
I want to try and be able to understand my work so that I can become a better programmer, I've left comments for the code that I dont fully understand, the rest I am comfortable with.
I would appreciate any one with the spare time to give me a few pointers and some help, thank you very much.
namespace GenericList
{
class Program
{
static void Main(string[] args)
{
/* I understand how objects work, but I dont fully understand
what is happening when I am passig through my constructer
name through the List */
List<Cities> cities = new List<Cities>();
/* I am passing matching arguments through each instance
of my cities List object but I still struggle to
visualise this process */
cities.Add(new Cities(1, "Durban - Home to the largest harbor in Africa"));
cities.Add(new Cities(2, "Johannesburg - The largest city in the country"));
cities.Add(new Cities(3, "Gqebetha - Also known as P.E, the friendly city"));
cities.Add(new Cities(4, "Bloemfontien - Host of the Rose Festival"));
cities.Add(new Cities(5, "Pretoria - South Africa's capital"));
Console.WriteLine("Which city would you like to know an interesting fact for?" +
"\n1) Durban" +
"\n2) Johannesburg" +
"\n3) Gqebetha" +
"\n4) Bloemfontien" +
"\n5) Pretoria" +
"\nEnter the number for the city you want:");
int answer = int.Parse(Console.ReadLine());
bool found = false;
for (int i = 0; i < cities.Count; i++)
{
if (cities[i].Id.Equals(answer))
{
Console.WriteLine("\nANSWER: " + cities[i].City);
found = true;
}
}
if (!found)
{
Console.WriteLine("\nWe couldn't find what you are looking for.");
}
}
}
class Cities
{
int id;
string city;
public Cities(int id, string city)
{
this.id = id;
this.city = city;
}
public int Id { get => id; set => id = value; }
public string City { get => city; set => city = value; }
}
}
List<Cities> cities = new List<Cities>();
Here you are creating a List, which contains only the object of Cities's class.
List is a array type data structure with various utilities(method).
Here you are using Add(), which append a new object to the list (in that case only Cities object as you declare in first line List<Cities>).
cities.Add(new Cities(1, "Durban - Home to the largest harbor in Africa"));
If I break down this line this will be:
// Creating a new Cities object
var newCity = new Cities(1, "Durban - Home to the largest harbor in Africa");
cities.Add(newCity );
Last line from the code block is appending newCity to the list of cities
Hope you understand now, If anything left unclear let me know
i rewrote with linq so you can see as a different approach. more easy reading code
void Main()
{
List<Cities> cities = new List<Cities>();
//add to cities array a new City class, since constructor accept 2 parameters you supply them on new object creation
Cities city;
city = new Cities(1, "Durban - Home to the largest harbor in Africa");
cities.Add(city);
city = new Cities(2, "Johannesburg - The largest city in the country");
cities.Add(city);
city = new Cities(3, "Gqebetha - Also known as P.E, the friendly city");
cities.Add(city);
city = new Cities(4, "Bloemfontien - Host of the Rose Festival");
cities.Add(city);
city = new Cities(5, "Pretoria - South Africa's capital");
cities.Add(city);
//different approach: create list with objects
cities = new List<Cities>()
{
new Cities(1, "Durban - Home to the largest harbor in Africa"),
new Cities(2, "Johannesburg - The largest city in the country"),
new Cities(3, "Gqebetha - Also known as P.E, the friendly city"),
new Cities(4, "Bloemfontien - Host of the Rose Festival"),
new Cities(5, "Pretoria - South Africa's capital")
};
Console.WriteLine("Which city would you like to know an interesting fact for?" +
"\n1) Durban" +
"\n2) Johannesburg" +
"\n3) Gqebetha" +
"\n4) Bloemfontien" +
"\n5) Pretoria" +
"\nEnter the number for the city you want:");
int answer = int.Parse(Console.ReadLine());
var result = cities
.Select((obj, index) => new { index, obj }) //set index for each object
.Where(w => w.index == answer)
.FirstOrDefault();
if (result == null)
Console.WriteLine("\nWe couldn't find what you are looking for.");
else
Console.WriteLine("\nANSWER: " + result.obj.City);
}
class Cities
{
//class properties
public int Id { get; set; }
public string City { get; set; }
//Parameterized Constructor https://www.tutlane.com/tutorial/csharp/csharp-constructors-with-examples#divcspzcst
public Cities(int id, string city)
{
Id = id;
City = city;
}
}
With
List<Cities> cities = new List<Cities>();
you create a new List-object that can store Cities objects. The generic type parameter <Cities> denotes the type of the list items and does not refer to the constructor. As an example, the following code would create a list that could store integer values:
List<int> lst = new List<int>();
The List<T> class is a generic type. The basic operations for a list like adding, removing, enumerating and so on are the same no matter what the type of the list items is. By creating a generic type, you can implement the functionality without knowing which types are used later on when you create an object. You might compare this to a method: when you implement the method, you define the parameters and their types; when you call the method, you supply the values of the parameters.
The code in the following line performs two tasks:
cities.Add(new Cities(1, "Durban - Home to the largest harbor in Africa"));
First, a new object of type Cities is created and initialized through the constructor. Second, it is added to the list. These are two separate steps that can also written like this:
// Create new object of type Cities
var city = new Cities(1, "Durban - Home to the largest harbor in Africa");
// Add newly created object to list
cities.Add(city);
As #BinRohan suggested in the comments, it might be a good idea the rename the Cities class to City because it defines a single city, not a collection of cities.
When you write this line of code
List<Cities> cities = new List<Cities>();
You instantiate an object being a List of "Cities". List is a "generic" type. It means it is able to handle any type and will behave the same. You could have a List or List, you'll manipulate different objects but the behaviour of List remains the same. You are not "passing" Cities to the List constructor, consider List as a type in itself.
It would be equivalent of declaring an array of Cities for example. There is no data in your list yet but it is ready to receive multiple instance of Cities.
Then when you write
cities.Add(New Cities{prop1=value,prop2=value...});
at run time it will do something like
var c = new Cities();
c.prop1=value;
c.prop2=value;
cities.Add(c);
It's kind of a shortcut which also make the code more readable.
Primary List:
enum CarMake
{
Ford, Toyota, Honda
}
Secondary List:
enum CarModel
{
Explorer, // Ford
Corolla, // Toyota
Camry, // Toyota
Civic, // Honda
Pilot // Honda
}
Is there some means of linking the 2 enum lists together?
So that when using CarMake the program will know which CarModels are linked?
No, as you want to achieve is not possible, but it would be possible using Dictionaries and string for CarModel
var dict = new Dictionary<CarMake,string[]>();
dict.Add(CarMake.Ford, new string[] { "Explorer" });
dict.Add(CarMake.Toyota, new string[] { "Corolla","Camry" });
dict.Add(CarMake.Honda, new string[] { "Civic","Pilot" });
then if you want to retrieve the cars from Honda, you call it as shown below:
var hondaCars = dict[CarMake.Honda]
If you, instead, want to retrieve the car-maker from the model you just call:
var carMaker = dict.FirstOrDefault(key => key.Value.Contains("Civic")).Key
You might wanna look into this.
Combine multiple enums into master enum list
allCars.AddRange(Enum.GetValues(typeof(CarModel)).Cast<Enum>());
allCars.AddRange(Enum.GetValues(typeof(CarMake)).Cast<Enum>());
Since if you make the list carModel into a master list in theory you get your answer
This question already has answers here:
How to flatten nested objects with linq expression
(4 answers)
Linq nested list expression
(2 answers)
Closed 7 years ago.
I have a list of a custom car object List<Car>. The car class has two properties 'BrandName' and 'Models' as defined below.
public class Car
{
public string BrandName {get; set;}
public List<string> Models {get; set;}
}
The data for the 'List` object is populated from an API as below. It returns close to 200 rows. For illustration purposes, the object has been instantiated with two items as below. The object is returned from the API with this structure and I have no control over how the data is structured and sent.
List<Car> listCarObj = new List<Car>(){
new Car(){ BrandName = "Mercedes", Models = new List<string>(){"Class A", "Class E"}},
new Car(){ BrandName = "BMW", Models = new List<string>(){"X Series", "E Series"}}
}
How do I convert this list to an IEnumerable or another List of an anonymous type having data in the below format using Linq?
var obj = new[] {new {brand = "Mercedes", model = "Class A"},
new {brand = "Mercedes", model = "Class E"},
new {brand = "BMW", model = "X Series"},
new {brand = "BMW", model = "E Series"}};
Thanks in advance..
here is a approach with SelectMany and a nested Select
var result = listCarObj.SelectMany(x => x.Models.Select(y => new { model = y,brand = x.BrandName }));
Why don't you make a linq query, in which you select every object from the listCarObj and, for every element from the list, get all the models and return an anonymous type?
Something like:
var obj = from p in listCarObj
from q in p.Models
select new {
brand=p.BrandName,
model = q
};
You can use SelectMany to flatten your Models and then project it like this:-
var result = listCarObj.SelectMany(x => x.Models,
(carObj, model) => new {
carObj.BrandName, model
});
If I have list of Author objects like
List<Author> authors = new List<Author>{
new Author { Id = 1, Name = "John Freeman"};
new Author { Id = 1, Name = "Adam Kurtz"};
};
this example is actually wrapped in static method which returns list of authors.
Inside my other object there is property Authors of type List<Author>.
Now I want to assign second author from the list to Authors property.
I thought that I can use Authors = GetAuthors()[1].ToList();
but I cannot access ToList() on index specified author.
to clarify
private static List<Author> GetAuthors() return list of authors (example above).
var someObject = new SomeObject()
{
Authors = // select only Adam Kurtz author using index
// and assign to Authors property of type List<Author>
};
If I understand you correctly, you want a List<Author> with a single author in it. Using ToList() on a single Author object is then not valid syntax.
Try this: Authors = new List<Author>() { GetAuthors()[1] };
You can't assign a single author to list<Author>, so you will have to create a list (of single author) to assign it..
Authors = new List<Author>() {GetAuthor()[1]};
I don't know, why you want to take based on index, ideally you should write a query based on ID of author to get value, so that it won't create any issue in future..
Like: Authors = new List<Author>() {GetAuthor().FirstOrDefault(x=>x.ID==2)};
A sollution with LINQ would be
GetAuthors().Skip(1).Take(1)
Edit: Ignore all that. You're working with lists.
What you actually need is to use GetRange:
GetAuthors().GetRange(1,1);
I have encountered a problem on how to define a two dimensional list(or array). Here is my data:
line1 line2 ... lineN
element1: name, phone, addr element1: name, phone, addr
element2: name, phone, addr element2: name, phone, addr
... ...
elementN: name, phone, addr elementN: name, phone, addr
The problem is that we don't know the exact lines and elements in each line. I tried to define the class People, containing members of name, phone, addr, etc, and use:
list<People> info = new list<People>();
That only defined one line - how can I define multiple lines?
People person = new People;
person.Address = "Address";
person.Phone = "11111";
List<People>() info = new List<People>();
info.Add(person);
will add a new instance of your People class (although Person would be a better name)
or potentially better would be a Dictionary with a suitable key
I'm not really sure what you are after but how about a list of dictionary, i.e. List<Dictionary<string, object>>? This will allow you to represent each person as a dictionary with a differing number of attributes.
Ok, after your question was edited is this what you are after: List<List<People>>?
You should have something like:
class SomePeople
{
SomePeople()
{
people = new list<People>();
}
public list<People> people;
}
List<SomePeople> info = new List<SomePeople>();
Or something like that, you get the point...
Try to use indexers here is the link from Microsoft Development Center http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx || http://msdn.microsoft.com/en-us/library/2549tw02.aspx
Another alternative would be to use a list of arrays, so you would declare :
List<People[]> peopleList = new List<People[]>();
And then use it like so :
peopleList.Add(new People[2]
{
new People { name = "name", phone = "123"...},
new People { name = "name", phone = "123"...}
});
peopleList.Add(new people[3]
{
// x 3 initializers
});
Hope that is equally as helpful!
Create a PeopleCollection class that extend Collection:
public class PeopleCollection : Collection<People>
{
}
It provides the base class for a generic collection. From msn documentation: The Collection class provides protected methods that can be used to customize its behavior when adding and removing items, clearing the collection, or setting the value of an existing item. (http://msdn.microsoft.com/en-us/library/ms132397.aspx)
Then you can define a list of People Collection, or a Dictionary, it depends on your object's access need. Like:
List morePeoples = new List();
Here you can put more "line", as you have described. Each "line" (list element) contains a collection of peoples.