c# get all properties in classProperty - c#

I have a List and I would like to know how much Properties are in each Item List.
Like the following example code I got four 'items' String in my Property class and I want to add it to a listview.
The problem is that I can't enumerate my property class Items as they are not a list. so I would like to count String Items in Property and then increment a variable to add it to the listview.
The main point is that my properties can be of any type (String, int and so on) and I would like to do a generic code for that.
Thanks in advance.
Code classList
public static class mylistitems
{
// public static List<Properties> mylistprop = new List<Properties>();
public static List<Properties> createdata(String name, String surname, String friend, String pet)
{
var DataProperties = new List<Properties>();
DataProperties.Add(new Properties { Name = name, SurName = surname, Friend = friend, Pet = pet });
return DataProperties;
}
public class Properties
{
public String Name { get; set; }
public String SurName { get; set; }
public String Friend { get; set; }
public String Pet { get; set; }
}
}
Code Caller
List<mylistitems.Properties> newlistitem = mylistitems.createdata("Derrick","Thomas","giordino","Max");
foreach (mylistitems.Properties propertyitem in newlistitem)
{
//Here!! Is it possible to get all the properties in a loop
ListViewItem LVitem = new ListViewItem();
LVitem.SubItems.Add(propertyitem.Name);
LVitem.SubItems.Add(propertyitem.SurName);
LVitem.SubItems.Add(propertyitem.Friend);
LVitem.SubItems.Add(propertyitem.Pet);
//how to change it like something like this
foreach (String item in propertyitem)
{ LVitem.SubItems.Add(item); }
}

Related

How to add items to existing list of objects?

I have three classes:
public class M2ArticleMain
{
public int Id { get; set; }
public List<M2ArticleAttributeWeb> Attribut_Web { get; set; }
}
public class M2ArticleAttributeWeb
{
public int Web_Id { get; set; }
public M2ArticleTmpMainSkus Variants { get; set; }
}
public class M2ArticleTmpMainSkus
{
public DateTime TimeAdded { get; set; }
public List<string> Skus { get; set; }
}
And I have two Lists in my code like this:
List<M2ArticleMain> data = new List<M2ArticleMain>();
List<M2ArticleAttributeWeb> attb = new List<M2ArticleAttributeWeb>();
In some part of my code firstly I (from foreach loop) add data to attb list where I add only only some data (because I don't have all data at this point), like this:
...
attb.Add(new M2ArticleAttributeWeb
{
Web_id = item.Id, //(item is from foreach loop)
Variants = null //this is **importat**, I left null for later to add it
});
Next, after I fill attb, I add all this to data list:
...
data.Add(new M2ArticleMain
{
Id = item.Id_Pk, //this is also from foreach loop,
Attribut_Web = attb //now in this part I have only data for Web_id and not Variants
}
Now my question is How to Add items later to data list to object Variants?
Something like this:
data.AddRange( "how to point to Variants" = some data);
The M2ArticleAttributeWeb type holding your Variants property is the member of a collection. That is, there are potentially many of them. You can reference an individual Variants property like this:
data[0].Attribut_Web[0].Variants
But you need to know which items you want to add map to which data and Attribut_Web indexes/objects in order to assign them properly. That probably means another loop, or even a nested loop. That is, you can see all of your Variants properties in a loop like this:
foreach(var main in data)
{
foreach(var attrw in main)
{
var v = attrw.Variants;
// do something with v
Console.WriteLine(v);
// **OR**
attrw.Variants = // assign some object
}
}
It's also much better practice to create your collection properties with the object, and then give them private set attributes:
public class M2ArticleMain
{
public int Id { get; set; }
public List<M2ArticleAttributeWeb> Attribut_Web { get; private set; } = new List<M2ArticleAttributeWeb>();
}
public class M2ArticleAttributeWeb
{
public int Web_Id { get; set; }
public M2ArticleTmpMainSkus Variants { get; set; }
}
public class M2ArticleTmpMainSkus
{
public DateTime TimeAdded { get; set; }
public List<string> Skus { get; private set; } = new List<string>();
}
Now instead of assigning Attribut_Web = attb, you would need to .Add() to the existing List.

Using dynamic to find a property

I have a set of messages which I cannot alter their structure, but all of them follow the same property structure after you drill into the first two. For example,
public class Animal {
public Dog Doggy { get; set; }
}
public class MixedAnimal {
public CatDog CatDoggy { get; set; }
}
public class Dog {
public Name name { get; set; }
public Age age { get; set; }
}
public class CatDog {
public Name name { get; set; }
public Age age { get; set; }
}
If I have a structure like this: SomeObj.Item where SomeObj is some object and Item is of type object which can hold either an Animal or MixedAnimal. How would I get to the value of either Dog or CatDog using the keyword dynamic?
I can get the top level object using SomeObj.Item as dynamic, and then do:
(SomeObj.Item as dynamic).Doggy.Name
but what I want is to just get the name without knowing the type of Item.
(SomeObj.Item as dynamic).(Something as dynamic).Name
Is this possible?
Using reflection is quite easy to resolve this problem. Something like this (general idea):
object animal = new Animal { Doggy = new Dog { age = 10, name = "Good boy" }};
var members = animal.GetType().GetMembers();
foreach (PropertyInfo member in members.Where(x => x is PropertyInfo))
{
if (member.PropertyType.Name == "Dog" || member.PropertyType.Name == "CatDog")
{
var propertyValue = member.GetValue(animal);
var propertyType = propertyValue.GetType();
var nameMember = propertyType.GetProperty("name");
var ageMember = propertyType.GetProperty("age");
var nameValue = nameMember.GetValue(propertyValue);
var ageValue = ageMember.GetValue(propertyValue);
Console.WriteLine($"Name: {nameValue}, Age: {ageValue}");
}
}
Everything you need to do additionally is providing list of type names which you want to process (like "Dog" or "CatDog" here).

Access Each Class Element In C# [duplicate]

This question already has answers here:
CS0120: An object reference is required for the nonstatic field, method, or property 'foo'
(9 answers)
Closed 3 years ago.
I am creating an application using Xamarin.Forms. I am trying to access each element in the list of MovieRent instances. I have a class that stores movie information:
public class MovieRent
{
public string movieTitle { get; set; }
public string movieReleaseDate { get; set; }
public int movieDuration { get; set; }
public double movieRentalPrice { get; set; }
public string movieRentType { get; set; }
public MovieRent(string mtitle, string mdate, int mtime, double mprice, string type)
{
movieTitle = mtitle;
movieReleaseDate = mdate;
movieDuration = mtime;
movieRentalPrice = mprice;
movieRentType = type;
}
}
addCartList is called to add a movie to a list. This creates/stores a list of movies.
class MoviesToRent
{
public List<MovieRent> movieRentList;
public MoviesToRent()
{
movieRentList = new List<MovieRent>();
}
public static MoviesToRent addCartList(string title, string date, int duration, double price, string type)
{
MoviesToRent movieList = new MoviesToRent();
MovieRentnewMovie = new MovieRent(title, date, duration, price, type);
movieList.movieRentList.Add(newMovie);
return movieList;
}
}
I am trying to access each instance, for example, the title of each movie in the list:
foreach (string movie in MoviesToRent.movieRentList)
{
this.Movie_Info.Text = movieRentList.title;
}
However, I get this error:
An object reference is required for the nonstatic field, method, or
property 'MoviesToRent.movieRentList'.
How can I overcome this error, so that I can access the movies that are in the list? I am trying display all movie info by looping through the list.
Thank you.
Your trying to access movieRentList as a static property. You need a instance of MoviesToRent and then access the list.
var movieRents = new MoviesToRent();
for (var movieRent in movieRents.movieRentList)
{
}
PS: In the example above, the list will be empty because I didnt add any object to it.
Okay, I think I first have to fix that naming and some glaring code issues. It is confusing the heck out of me:
public class Movie
{
public string movieTitle { get; set; }
public string movieReleaseDate { get; set; }
public int movieDuration { get; set; }
public double movieRentalPrice { get; set; }
public string movieRentType { get; set; }
public MovieRent(string mtitle, string mdate, int mtime, double mprice, string type)
{
movieTitle = mtitle;
movieReleaseDate = mdate;
movieDuration = mtime;
movieRentalPrice = mprice;
movieRentType = type;
}
}
class MoviesRentCart
{
public List<Movie> movieRentList;
public MoviesToRent()
{
movieRentList = new List<MovieRent>();
}
public static MoviesToRent addCartList(string title, string date, int duration, double price, string type)
{
//What does this line do here?
//MoviesToRent movieList = new MoviesToRent();
//fixed missing space
Movie newMovie = new Movie(title, date, duration, price, type);
movieList.movieRentList.Add(newMovie);
return movieList;
}
}
Then in your actuall code, you need a instance of MovieRentCart. Same way you make an instance of Movie. To that instance, you add the elements. Over that instance's movieRentList, you itterate.
The error happens because you're trying to access movieRentList as if it where a static field member of the class MoviesToRent. You need an instance of MoviesToRent like so:
var moviesToRent = new MoviesToRent();
And to access the title of each movie in the list do:
foreach (MovieRent movie in moviesToRent.movieRentList)
{
//The movie title is movie.movieTitle
}

Object’s Parent Current Instance

Having the following object(s):
public class Employee
{
public string LastName { get; set; } = "";
internal class SubordinateList<T> : List<T>, IPublicList<T> where T : Employee
{
public new void Add(T Subordinate) { }
}
public IPublicList<Employee> Subordinates = new SubordinateList<Employee>();
}
The SubordinateList object is inside the Employee object making Employee the parent of SubordinateList in a certain way.
If we put this code below:
Anakin = New Employee();
Luke = New Employee();
Anakin.Subordinates.Add(Luke);
The third line will trigger the method “Add” of SubordinateList.
I would like to get the Current Instance for the Parent of SubordinateList like this:
public new void Add(T Subordinate)
{
T Manager = Subordinate.ParentInstance;
// then it will be possible to see the current value of
// the property "LastName" for Anakin with "Manager.LastName"
}
You can't do it that way since you don't have a reference to the manager. This is how I would implement it:
public class Employee
{
public string FirstName { get; set; } = "";
public string LastName { get; set; } = "";
public string HiredDate { get; set; } = "";
private List<Employee> _subordinates = new List<Employee>();
public ReadOnlyCollection<Employee> Subordinates => _subordinates.AsReadOnly();
public void AddSubordinate(Employee employee)
{
_subordinates.Add(Employee);
//the manager is 'this'
var managerLastName = this.LastName;
}
}
Exposing the subordinate list as a ReadOnlyCollection allows other classes to read the list, but prevents them from updating the list directly. So only the AddSubordinate() method can be used to add employees, where you can do what you need with the manager's information.

Databind a List with a Template to a Dropdown Datasource

I have a Template via:
public class OwnedProvinces
{ public Guid ProvinceID;
public string ProvinceName;
}
And I created a list with this template here:
List<OwnedProvinces> getinfo = (from upi in db.Utopia_Province_Data_Captured_Gens
where upi.Owner_User_ID == SQLStatementsCS.UserID()
where upi.Province_Name != string.Empty
select new OwnedProvinces { ProvinceName = upi.Province_Name, ProvinceID = upi.Province_ID}).ToList();
The problem with this when I try to bind it to the Dropdown list like so:
ddlSelectProvince.DataTextField = "ProvinceName";
ddlSelectProvince.DataValueField = "ProvinceID";
ddlSelectProvince.DataSource = getinfo;
ddlSelectProvince.DataBind();
It throws the Error:
DataBinding: 'OwnedProvinces' does not contain a property with the name 'ProvinceName'.
Basically, it can't find the property ProvinceName in the List, but makes no sense to me. If I do an anonymous query, it works, but when I assign it to the class OwnedPRovinces, it throws this error...
Try to change the class like this
public class OwnedProvinces
{
public Guid ProvinceID { get; set; }
public string ProvinceName { get; set; }
}
The problem is that ProvinceID and ProvinceName are member variables not properties.
Problem is with your declaration -
public Guid ProvinceID;
public string ProvinceName;
are the fields, but not the properties. You should either change their definition or you should try to implement the IDataBindable interface, as written here:
http://www.primaryobjects.com/CMS/Article95.aspx
#region IDataBindable Members
public List<NameValueType> ToList()
{
List<NameValueType> resultList = new List<NameValueType>();
using (DataContext context = new DataContext())
{
List<Monster> itemList = context.Monsters.ToList();
foreach (Monster item in itemList)
{
resultList.Add(new NameValueType(item.MonsterId.ToString(), item.Name));
}
}
return resultList;
}
#endregion

Categories