How to access properties inside multiple model - c#

When joining multiple models, I can't access its properties in controller.
public class BirdModel
{
public IEnumerable<BirdFile> BirdFils { get; set; }
public IEnumerable<BirdFileDetail> BirdFileDetails { get; set; }
}
public partial class BirdFile
{
public int ID{ get; set; }
public string Name{ get; set; }
}
Is it possible to access like this
BirdModel b = new BirdModel();
b.BirdFile.ID

You problem with b.BirdFile.ID is that you are trying to access the property or a collection of objects that you have not initialised.
You need to create an instance of the encapsulating class, BirdModel then create an instance of your BirdFile collection and add values to it. From there you can get the specific "BirdFile" within your collection via iteration and then access its properties.
A small example below:
class Program
{
static void Main(string[] args)
{
var bm = new BirdModel();
bm.BirdFils = new List<BirdFile>
{
new BirdFile {ID = 1, Name = "Bird A"},
new BirdFile {ID = 2, Name = "Bird B"}
};
bm.BirdFils.ToList().ForEach(x => Console.WriteLine($"Name: {x.Name}, ID: {x.ID}"));
Console.ReadKey();
}
}
public class BirdModel
{
public IEnumerable<BirdFile> BirdFils { get; set; }
}
public partial class BirdFile
{
public int ID { get; set; }
public string Name { get; set; }
}

BirdModel contains a collection of BirdFile, so to access them you should write something like:
// create a new model
BirdModel b = new BirtdModel()
// create the instance of BirdFile list
b.BirdFils = new List<BirdFile>()
// add an item (just an example)
b.BirdFils.Add(new BirdFile{ ID = 1, Name = "Bird1"}
// Access to the previously created BirdFile
BirdFile bf = b.BirdFils[0]

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.

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.

an array list with n rows and four columns in c#

I need a clear example that shows me how to define a list that has n rows and 4 columns and how to use it. I need a list to save my data like the below image. as you see this could be a dictionary.
You need to create a class with all the above properties
public class Sample
{
public string vocabulary { get; set; }
public string meaning { get; set; }
public int number { get; set; }
public int group { get; set; }
}
and then you can create a List of type Sample,
List<Sample> yourList = new List<Sample>();
You can add items to the list as below
yourList.Add(new Sample { vocabulary = "massive", meaning = "very big", number = 5, group = 15 });
You can access them later like this, if you want the first element,
var result = yourList[0];
this is the easiest and best way of doing it. You need to create a new class and then create new instances of the class and then add it to the list and then use LINQ to get the data out
void Main()
{
var list = new List<myClass>()
list.Add(new myClass() {
Vocabluary = "Vocabluary ",
Meaning = "meaning",
Number = 1,
Group = 2})
}
public class myClass
{
public string Vocabluary { get; set; }
public string Meaning { get; set; }
public int Number { get; set; }
public int Group { get; set; }
}
yes... as Sajeetharan mentioned, with a custom class you can create an any dimensions List. but i don't think you need to think about dimension in C#... it is a bit more high level than that.
just simply create a class and put everything you need in it...
public class CustomClass{
public string d1;
public int d2;
public string d3;
public string d4;
...
//you can easily create a N dimension class
}
to access it and apply it
public void Main(){
List<CustomClass> list = new List<CustomClass>();
CustomClass cc = new CustomClass();
cc.d1 = "v1";
cc.d2 = 0; //v2
list.Add(cc);
//to access it
foreach(CustomClass tmpClass in list)
{
string d1Value = tmpClass.d1;
int d2Value = tmpClass.d2;
}
}

Singleton class for multidimensional data

I am using ASP.NET 3.5 with C#2008.
I have a table with data like below :
Id Code Message Details
-- ---- ------ ------------
1 111 xxxxx xxxxxxxxxxx
2 222 yyyyy yyyyyyyyyyy
3 333 zzzzz zzzzzzzz
and so on..
This is static data and I want to use it across application.
I have created a class with properties as below :
public class CodeDetails
{
public int Id { get; set; }
public int Code { get; set; }
public string message { get; set; }
public string details { get; set; }
}
And created another class codeDetailsList to whom I want to make as singletone as below :
public class codeDetailsList
{
private List<CodeDetailst> lstCodeDetailst;
private CodeDetailst()
{
lstCodeDetails = new List<CodeDetails>();
}
}
Now, what I want to do is, I want to add the items of above given tabular data into this singleton class's list and want to access it throughout application.
My question is how to add the items and access them?
Similar to Varun's answer, I just wanted to do a full implementation.
public class CodeDetailsList
{
private static readonly CodeDetailsList _instance = new CodeDetailsList();
public static CodeDetailsList Instance
{
get { return _instance; }
}
public ReadOnlyCollection<CodeDetails> lstCodeDetailst { get; private set; }
private codeDetailsList()
{
var masterList = new List<CodeDetails>();
masterList.Add(new CodeDetails(1, 111, "xxxxx", "xxxxxxxxxxx"));
masterList.Add(new CodeDetails(2, 222, "yyyyy", "yyyyyyyyyyy"));
//... And so on ...
//mark the list as read only so no one can add/remove/replace items in the list
lstCodeDetailst= masterList.AsReadOnly();
}
}
public class CodeDetails
{
public CodeDetails(id, code, message, details)
{
Id = id;
Code = code;
Message = message;
Details = details;
}
//Mark the setters private so no one can change the values once set.
public int Id { get; private set; }
public int Code { get; private set; }
public string Message { get; private set; }
public string Details { get; private set; }
}
The constructor for CodeDetailsList will be called once when you first try to access Instance (If you had other static members in the class the constructor would run on the first time any static member was called).
Because lstCodeDetaillst is a ReadOnlyCollection callers will not be able to add, remove, or replace objects in the list. Also because now CodeDetails has private setters all of the items in it are effectively "read only" too.
public class CodeDetailsList
{
public static readonly CodeDetailsList Instance = new CodeDetailsList();
public List<CodeDetails> ListCodeDetails { get; private set; }
private CodeDetailsList()
{
ListCodeDetails = new List<CodeDetails>
{
new CodeDetails { Id = 1, Code = 1, Details = "xxxxx", Message = "xxxxx"},
new CodeDetails { Id = 2, Code = 2, Details = "yyyyy", Message = "yyyy"} // ...
};
}
}
You should initialize the data in the constructor of codeDetailsList. The constructor should remain private to insure you do not create a new instance. Access the data using the Instance field on CodeDetailsList.
Did you intentionally omit the getInstance() method from your Singleton class? anyway...
The add might look something like:
CodeDetails codeDetails = new CodeDetails();
codeDetails.setId("id1");
codeDetails.setCode("code1");
codeDetails.setMessage("message1");
codeDetails.setDetails("details1");
(CodeDetailsList.getInstanceMethod()).add(codeDetails);
To access:
CodeDetails codeDetails = (CodeDetails)(CodeDetailsList.getInstaceMethod()).get(0);
You can put it in a loop if you have number of records
Hope this helps

Model binding for nested objects

I have a class
public class Offer
{
public Int32 OfferId { get; set; }
public string OfferTitle { get; set; }
public string OfferDescription { get; set; }
}
and another class
public class OfferLocationViewModel
{
public Offer Offer { get; set; }
public Int32 InTotalBranch { get; set; }
public Int32 BusinessTotalLocation { get; set; }
}
Now in my controller I have the following
public ActionResult PresentOffers(Guid id)
{
DateTime todaysDate=Utility.getCurrentDateTime();
var rOffers=(from k in dc.GetPresentOffers(id,todaysDate)
select new OfferLocationViewModel()
{
Offer. //I dont get anything here..
}).ToList();
return PartialView();
}
Now the problem is in my controller, I can not access any property of the 'Offer' class !!
I thought, since i am creating a new OfferLocationViewModel() and this has a property of type 'Offer', I will be able to access the properties..But I can not.
Can anyone give me some idea about how to do that?
In a class initializer like new OfferLocationViewModel { ... } you can only set the immediate properties, i.e. 'Offer = new Offer()'.
You can't access the contained type's properties through the initializer.
Though you can initialize the view model's Offer to a new Offer with the given properties like this:
var rOffers = (from k in dc.GetPresentOffers(id,todaysDate)
select new OfferLocationViewModel {
Offer = new Offer {
OfferId = ...,
OfferTitle = ...,
OfferDescription = ...
}
}).ToList();

Categories