I need some help on how to initialize the below object with some sample values in the Main method to perform some action.
Since I am new to C# please guide me to where can i get this information
class MobOwner
{
public string Name { get; set; }
public List<string> Mobiles { get; set; }
}
Simply initialize it within your constrcutor:
class MobOwner
{
public string Name { get; set; }
public List<string> Mobiles { get; set; }
public MobOwner() {
this.Mobiles = new List<string>();
}
}
You can also define a constructor that direclty puts the right values into your list:
class MobOwner
{
public string Name { get; set; }
public List<string> Mobiles { get; set; }
public MobOwner(IEnumerable<string> values) {
this.Mobiles = values.ToList();
}
}
Which you can than call like new MobOwner(new[] { "Mario", "Hans", "Bernd" })
First of all, I doubt if you really want set; in the Mobiles property:
typically we add/update/remove items in the list, but not assign the list as whole
MobOwner sample = new MobOwner(...);
sample.MobOwner.Add("123");
sample.MobOwner.Add("456");
sample.MobOwner.RemoveAt(1);
sample.MobOwner[0] = "789";
sample.MobOwner = null; // we, usually, don't want such code
The implementation can be
class MobOwner {
public string Name { get; set; }
public List<string> Mobiles { get; } = new List<string>();
public MobOwner(string name, IEnumerable<string> mobiles): base() {
if (null == name)
throw new ArgumentNullException("name");
if (null == mobiles)
throw new ArgumentNullException("mobiles");
Name = name;
Mobiles.AddRange(mobiles);
}
}
you can make and instance and set the variable
var owner = new MobOwner();
owner.Mobiles = new List<string>{"first", "second"};
or like so
var owner = new MobOwner {Mobiles = new List<string> {"first", "second"}};
recommanded way is to use a contructor and make the set properties private
class MobOwner
{
public string Name { get; private set; }
public List<string> Mobiles { get; private set; }
// constructor
public MobOwner(string name, List<string> mobiles)
{
Name = name;
Mobiles = mobiles;
}
}
var mobOwner = new MobOwner()
{
Name = "name";
Mobiles = new List<string>()
{
"mob1",
"mob2",
"mob3"
};
};
This creates one MobOwner object containing a list with one item
MobOwner item = new MobOwner()
{
Name = "foo",
Mobiles = new List<string>() { "bar" }
};
Another way is to add a constructor to simplify instanciation
class MobOwner
{
public string Name { get; set; }
public List<string> Mobiles { get; set; }
public MobOwner(string Name, params string[] Mobiles)
{
this.Name = Name;
this.Mobiles = new List<string>(Mobiles);
}
}
usage:
MobOwner item2 = new MobOwner("foo", "bar", "bar");
If I'm getting your purpose correctly you want to initialize these values in the "Main" method.
Constructor is a good way to initialize your properties with default values whenever you create an instance of your class.
But if you want to initialize them in another place make an instance of your class and then you can give values to its public members. like this:
MobOwner mobOwner = new MobOwner();
mobOwner.Name = "Jimmy";
mobOwner.Mobiles = new List<string>{119, 011};
or in a more modern way you can change the syntax like this(although they are the same):
MobOwner mobOwner = new(){
Name = "Jimmy",
Mobiles = new List<string>{119, 011}
};
Related
I want to get the property name and the value from object and pass them to the list.
i dont want to pass one by one property and value to the list like commented in my code. want to use loop and add name and value dynamically
public class ParametersList
{
public string Name { get; set; }
public dynamic Value { get; set; }
}
public class BookVM
{
public string AuthorName{ get; set; }
public string CoverUrl { get; set; }
public int AuthorIds { get; set; }
}
public List<Book> Addgetallbooks(BookVM BookVM)
{
List<ParametersList> obj = new List<ParametersList>();
//List<ParametersList> obj = new List<ParametersList>
//{
// new ParametersList{Name=nameof(BookVM.AuthorIds),Value=BookVM.AuthorIds},
// new ParametersList{Name=nameof(BookVM.AuthorName),Value=BookVM.AuthorName},
// new ParametersList{Name=nameof(BookVM.CoverUrl),Value=BookVM.CoverUrl}
//};
var getdata = _opr.GetBooks1(obj);
return getdata;
}
You need to use reflection, but not sure if you should do it :)
[TestMethod]
public void Foo()
{
var book = new BookVM() { AuthorIds = 1, AuthorName = "some name", CoverUrl = "some cover url" };
var result = GetParameters(book);
result.Should().BeEquivalentTo(new[]
{
new ParametersList { Name = nameof(BookVM.AuthorIds), Value = 1 },
new ParametersList() { Name = nameof(BookVM.AuthorName), Value = "some name" },
new ParametersList { Name = nameof(BookVM.CoverUrl), Value = "some cover url" }
});
}
private static List<ParametersList> GetParameters(BookVM book)
{
return typeof(BookVM).GetProperties().Select(p => new ParametersList
{
Name = p.Name, Value = p.GetValue(book)
}).ToList();
}
Basically how do I access the component of a structure in my Sorted List (keys are strings and values are the structure). The structure is Section and one of the components of it is called name. How do I access that component. linkedList.GetByIndex(i).name doesn't work.
To illustrate my comment:
struct A
{
public string name;
}
static void Demo()
{
// using System.Collections.Generic;
SortedList<string, A> list = new SortedList<string, A>();
list.Add("k0", new A { name = "name0" });
var name0 = list.Values[0].name;
}
To access the first struct in the example list, use list.Values[0] or list["k0"]. You can then access the .name property of the struct.
As far as I understood, the Post from #AxelKemper should help.
A simple example:
public struct Section
{
public string Name { get; set; }
public SortedList<string, string> List { get; set; }
}
public class SectionsClass
{
public string Indentifier { get; set; }
public SortedList<string, Section> Sections { get; set; }
}
public class MyTestClass
{
public MyTestClass()
{
var sc = new SectionsClass
{
Indentifier = "A",
Sections = new SortedList<string, Section> {
{"1", new Section { Name = "AA" } },
{"2", new Section { Name = "AB" } },
}
};
Debug.WriteLine(sc.Sections.ElementAt(0).Value.Name); // AA
}
}
UPDATE: insert "using System.Linq;" as "ElementAt" is an extension method from Linq
I've been working on using reflection but its very new to me still. So the line below works. It returns a list of DataBlockOne
var endResult =(List<DataBlockOne>)allData.GetType()
.GetProperty("One")
.GetValue(allData);
But I don't know myType until run time. So my thoughts were the below code to get the type from the object returned and cast that type as a list of DataBlockOne.
List<DataBlockOne> one = new List<DataBlockOne>();
one.Add(new DataBlockOne { id = 1 });
List<DataBlockTwo> two = new List<DataBlockTwo>();
two.Add(new DataBlockTwo { id = 2 });
AllData allData = new AllData
{
One = one,
Two = two
};
var result = allData.GetType().GetProperty("One").GetValue(allData);
Type thisType = result.GetType().GetGenericArguments().Single();
Note I don't know the list type below. I just used DataBlockOne as an example
var endResult =(List<DataBlockOne>)allData.GetType() // this could be List<DataBlockTwo> as well as List<DataBlockOne>
.GetProperty("One")
.GetValue(allData);
I need to cast so I can search the list later (this will error if you don't cast the returned object)
if (endResult.Count > 0)
{
var search = endResult.Where(whereExpression);
}
I'm confusing the class Type and the type used in list. Can someone point me in the right direction to get a type at run time and set that as my type for a list?
Class definition:
public class AllData
{
public List<DataBlockOne> One { get; set; }
public List<DataBlockTwo> Two { get; set; }
}
public class DataBlockOne
{
public int id { get; set; }
}
public class DataBlockTwo
{
public int id { get; set; }
}
You might need something like this:
var endResult = Convert.ChangeType(allData.GetType().GetProperty("One").GetValue(allData), allData.GetType());
Just guessing, didn't work in C# since 2013, please don't shoot :)
You probably want something like this:
static void Main(string[] args)
{
var one = new List<DataBlockBase>();
one.Add(new DataBlockOne { Id = 1, CustomPropertyDataBlockOne = 314 });
var two = new List<DataBlockBase>();
two.Add(new DataBlockTwo { Id = 2, CustomPropertyDatablockTwo = long.MaxValue });
AllData allData = new AllData
{
One = one,
Two = two
};
#region Access Base Class Properties
var result = (DataBlockBase)allData.GetType().GetProperty("One").GetValue(allData);
var oneId = result.Id;
#endregion
#region Switch Into Custom Class Properties
if (result is DataBlockTwo)
{
var thisId = result.Id;
var thisCustomPropertyTwo = ((DataBlockTwo)result).CustomPropertyDatablockTwo;
}
if (result is DataBlockOne)
{
var thisId = result.Id;
var thisCustomPropertyOne = ((DataBlockOne)result).CustomPropertyDataBlockOne;
}
#endregion
Console.Read();
}
public class AllData
{
public List<DataBlockBase> One { get; set; }
public List<DataBlockBase> Two { get; set; }
}
public class DataBlockOne : DataBlockBase
{
public int CustomPropertyDataBlockOne { get; set; }
}
public class DataBlockTwo : DataBlockBase
{
public long CustomPropertyDatablockTwo { get; set; }
}
public abstract class DataBlockBase
{
public int Id { get; set; }
}
I'm working with KnockoutMVC and it requires strongly type models to use inside the VIEW. I have tried multiple variations of the examples on KnockoutMVC's site including using ENUMS and still could not get it to work. Perhaps this is a problem with the setup of my models.
MODELS
public class PhoneNumber
{
public List<NumberTypeClass> Types { get; set; }
//public NumberType enumType { get; set; }
//public enum NumberType
//{
// Work,
// Home,
// Mobile,
// Fax
//}
private string _number;
[StringLength(14, MinimumLength = 10, ErrorMessage = "Please use (123) 456-7890 format"), Required]
public string Number
{
get
{
this._number = BeautifyPhoneNumber(this._number);
return this._number;
}
set
{
this._number = value;
}
}
public string Extension { get; set; }
public static String BeautifyPhoneNumber(string numberToBeautify)
{
//beautifyNumberCode
}
}
public class NumberTypeClass
{
public int Id { get; set; }
public string NumberType { get; set; }
}
public class VendorsEditorVendorModel
{
public string FirstName {Get;set;}
public string LastName {get;set;}
public List<Address> Address {get;set;}
public List<PhoneNumber> Phones {get;set;}
}
public class VendorsEditorModel
{
public List<VendorsEditorVendorModel> Vendors {get;set;}
}
CONTROLLER
public class VendorsEditorController : BaseController
{
public ActionResult CreateVendors()
{// VendorsEditor/CreateVendors
var vendor = new VendorsEditorModel();
vendor.Vendors = new List<VendorsEditorVendorModel>();
vendor.Vendors[0].Phones[0].Types = new List<NumberTypeClass>
{
new NumberTypeClass{Id = 0, TypeName = "Mobile"},
new NumberTypeClass{Id = 0, TypeName = "Work"},
new NumberTypeClass{Id = 0, TypeName = "Home"}
};//this throws an error because there is no Vendors[0] ...but how would i populate this list for every Vendor?
return View(vendor);
}
}
You cannot call an empty collection by index [x]. You need to fill your collection from a database or what not before you can access items in it. If you are just trying to add items to a collection, this is how you do it:
var vendor = new VendorsEditorModel
{
Vendors = new List<VendorsEditorVendorModel>
{
new VendorsEditorVendorModel
{
Phones = new List<PhoneNumber>
{
new PhoneNumber
{
Types = new List<NumberTypeClass>
{
new NumberTypeClass {Id = 0, NumberType = "Mobile"}
}
}
}
}
}
};
If you just want to add the types to an already populated collection, you can do the following:
foreach (var phone in vendor.Vendors.SelectMany(item => item.Phones))
{
phone.Types = new List<NumberTypeClass>
{
new NumberTypeClass{Id = 0, NumberType = "Mobile"},
new NumberTypeClass{Id = 0, NumberType = "Work"},
new NumberTypeClass{Id = 0, NumberType = "Home"}
};
}
I have a dataset which returns a couple of contact information in string(Phone, mobile, skype). I created an object with a Dictionary property where i can put the contact information in a key value pair. The problem is, I am assigning the values of the object using Linq. Hope somebody can help. Here is my code:
public class Student
{
public Student()
{
MotherContacts = new ContactDetail();
FatherContacts = new ContactDetail();
}
public ContactDetail MotherContacts { get; set; }
public ContactDetail FatherContacts { get; set; }
}
public class ContactDetail
{
public ContactDetail()
{
Items = new Dictionary<ContactDetailType, string>();
}
public IDictionary<ContactDetailType, string> Items { get; set; }
public void Add(ContactDetailType type, string value)
{
if(!string.IsNullOrEmpty(value))
{
Items.Add(type, value);
}
}
}
public enum ContactDetailType
{
PHONE,
MOBILE
}
Here's how I assign value to the Student object:
var result = ds.Tables[0].AsEnumerable();
var insuranceCard = result.Select(row => new Student()
{
MotherContacts.Items.Add(ContactDetailType.PHONE, row.Field<string>("MotherPhone"),
MotherContacts.Items.Add(ContactDetailType.MOBILE, row.Field<string>("MotherMobile")
}).FirstOrDefault();
The compiler says that the MotherContacts is not recognized in the context. What should I do?
I think your code should look like:
var insuranceCard = result.Select(row =>
{
var s = new Student();
s.MotherContacts.Items.Add(ContactDetailType.PHONE, row.Field<string>("MotherPhone");
s.MotherContacts.Items.Add(ContactDetailType.MOBILE, row.Field<string>("MotherMobile");
return s;
}).FirstOrDefault();
You are using the object initializer syntax in a wrong way. The correct use is:
new Student{MotherContacts = value} where value must be a ContactDetail.