ASP.NET add items to List from Class - c#

I have this class here:
public class CP_VIP_Preview_TimeSlots
{
public int id { get; set; }
[DisplayName("Time Slots")]
public string timeSlot { get; set; }
[DisplayName("Date Slots")]
public string dateSlot { get; set; }
}
public class CPVIPPreviewTimeSlots : DbContext
{
public DbSet<CP_VIP_Preview_TimeSlots> Data { get; set; }
}
Now what I am trying to do is put each item of the class into a List, I have created this list:
List<string> newList = new List<string>();
What I am looking to add to this list is a the id and timeSlot and DateSlot, however I want the timeSlot and DateSlot as a combined string. So my new list will have id and some string called timeDateSlot...I hope this make sense, how would I do this?

If you have a CP_VIP_Preview_TimeSlots called test:
newList.add(test.id.ToString());
newList.add(test.timeSlot + test.dateSlot);
However, you do not get to choose identifiers for these string.

If you really don't want to store a list of your TimeSlots class then what you need is a list of KeyValuePairs.
List<KeyValuePair<int,string>>
and in this you can add:
List<KeyValuePair<int,string>> myList = new List<KeyValuePair<int,string>>();
myList.Add(new KeyValuePair<int, string>(test.id.ToString(), test.timeSlot + test.dateSlot));

List<CP_VIP_Preview_TimeSlots> newList = new List<CP_VIP_Preview_TimeSlots>();
foreach(var x in CPVIPPreviewTimeSlots){ //whatever your db data is
newList.add(x); //add an instance to list
}
Something like this might help. Then you could display like so,
var x = newList.first();
string combined = x.timeSlot + x.dateSlot;

You can add an extra property to your class to get the correct string that is accessible anywhere:
public class CP_VIP_Preview_TimeSlots
{
public int id { get; set; }
[DisplayName("Time Slots")]
public string timeSlot { get; set; }
[DisplayName("Date Slots")]
public string dateSlot { get; set; }
public string combinedString
{
get
{
return timeSlot + " " + dateSlot;
}
}
}
This can then also be used in your other question
DropDownList1.DataSource = newList;
DropDownList1.DataTextField = "combinedString";
DropDownList1.DataValueField = "timeSlot";
DropDownList1.DataBind();

If you want to identify data using Id you can use the following code
foreach(CP_VIP_Preview_TimeSlots d in CPVIPPreviewTimeSlots.Data)
{
List<KeyValuePair<int,string>> lstIdWiseData = new List<KeyValuePair<int,string>>();
lstIdWiseData.Add(new KeyValuePair<int,string>(d.Id, string.Concat(d.timeSlot, d.dateSlot )));
}
If your id is not unique you can replace KeyValuePair<int,string> with Tuple<int,string> in the above code

Related

Add class properties from the List and put them into the string together with a comma as a delimiter

Although the thing I want to do seems be really trivial I can not find a way to achieve what I want. I know there exist multiple questions how to put class properties into the list together and separate it by a comma like that on SO, but none of them seemed to be relevant to my case.
I have a class Form defined as follows:
public class Form
{
public string CustomerName { get; set; }
public string CustomerAdress { get; set; }
public string CustomerNumber { get; set; }
public string OfficeAdress { get; set; }
public string Date { get; set; }
public Boolean FunctionalTest { get; set; }
public string Signature { get; set; }
public Form()
{
}
}
In the MainPage.xaml.cs, I create a List<Form> with the Form class properties and subsequently I would like to create a string with all of those class properties separated by a comma. For that case I use basic Join method with Select which converts any kinds of objects to string.
I do that by createCSV method inside MainPage.xaml.cs :
void createCSV()
{
var records = new List<Form>
{
new Form {CustomerName = customerName.Text,
CustomerAdress = customerAdress.Text,
CustomerNumber = customerNumber.Text,
OfficeAdress = officeAdress.Text,
Date = date.Date.ToString("MM/dd/yyyy"),
FunctionalTest = testPicker.ToString()=="YES" ? true : false,
Signature = signature.Text
}
};
string results = String.Join(",", (object)records.Select(o => o.ToString()));
}
The problem is instead of the desirable outcome which is:"Mark Brown,123 High Level Street,01578454521,43 Falmouth Road,12/15/2020,false,Brown"
I am getting: "System.Linq.Enumerable+SelectListIterator'2[MyApp.Form,System.String]"
PS. As you have noticed I am newbie in C#. Instead of non constructive criticism of the code, please for a valuable reply which would help me to understand what am I doing wrong.
Thanks in advance
In the Form class, You can override the ToString() method and use System.Reflection to get your comma string.
Form.cs
public class Form
{
public string CustomerName { get; set; }
public string CustomerAdress { get; set; }
public string CustomerNumber { get; set; }
public string OfficeAdress { get; set; }
public string Date { get; set; }
public bool FunctionalTest { get; set; }
public string Signature { get; set; }
public override string ToString()
{
string modelString = string.Empty;
PropertyInfo[] properties = typeof(Form).GetProperties();
foreach (PropertyInfo property in properties)
{
var value = property.GetValue(this); // you should add a null check here before doing value.ToString as it will break on null
modelString += value.ToString() + ",";
}
return modelString;
}
}
Code
List<string> CSVDataList = new List<string>();
List<Form> FormList = new List<Form>();
...
foreach (var data in FormList)
{
CSVDataList.Add(data.ToString());
}
Now you have a list of string CSVDataList with each Form object's data in comma style
P.S.
for DateTime
var value = property.GetValue(this);
if(value is DateTime date)
{
modelString += date.ToString("dd.MM.yyyy") + ",";
}

unable to get list of elements in list

i have 2 model classes
public class ProductOptionRequest
{
public string Name { set; get; }
public List<ProductValuesRequest> productValues { get; set; }
}
public class ProductValuesRequest
{
public string ValueName { get; set; }
}
public class ProductOptionValue
{
public int OptionId { get; set; }
public String ValueName { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
and wrote one bs method and passing parameter value as value names. but I'm unable to get those values in a list object as productValues. May I know the solution, please.
public async Task<ReturnString> SaveProductOption(ProductOptionRequest request)
{
request.productValues = new List<ProductValuesRequest>();
foreach (ProductValuesRequest valueRequest in request.productValues)
{
ProductOptionValue res = new ProductOptionValue();
res.ValueName = valueRequest.ValueName;
object response = await productOptionValueRepository.InsertAsync(res, true);
}
}
In the first line of your method, you are replacing the productValues property of request object with a new empty list, :
request.productValues = new List<ProductValuesRequest>();
Therefore, in foreach loop, you are iterating on an empty list.
Remove the first line and see if you still have any issues.
You are assigning an emplty list to productValues as
request.productValues = new List() and trying to iterate the empty list.

C# Copy List items to Object Arrays

I have a list created from a stored procedure using EF6.0
I have also created 3 classes
public class Resas
{
public string todo{ get; set; }
public string prop { get; set; }
public string Code { get; set; }
public string statusCode { get; set; }
public string checkin { get; set; }
public string checkout { get; set; }
public List<profiles> profiles { get; set; }
}
public class profiles
{
public string action { get; set; }
public string id { get; set; }
public string profileType { get; set; }
public string title { get; set; }
public string firstName { get; set; }
public string middleName { get; set; }
public string lastName { get; set; }
public List<emailAddresses> emailAdresses { get; set; }
}
public class emailAddresses
{
public string emailAddress { get; set; }
public string emailAddress2 { get; set; }
}
I am doing a for-loop in the list and I need to get certain columns and put it in the array (I will put two, to keep it simple)
myEntities db = new myEntities();
List<rev_Result> revList = new List<rev_Result>();
revList.Clear();
revList = db.rev().ToList();
for (int i = 0; i < revList.Count(); i++)
{
Resas resas = new Resas();
profiles[] profiles = new profiles[1];
resas.todo = revList[i].todo;
resas.profiles[0].lastName = revList[i].lastName;
}
I am not familiar with C# as you can see from the psedo-code above.
I cannot figure out how to feed the Resas with data and then its Profile with data and then move to the next Resas entry.
Any help appreciated.
That's fairly simple using Linq:
Resas resas = new Resas();
resas.profiles = revList
.Select(x => new profiles() { action = x.todo, lastName = x.lastName })
.ToList();
What's happening here is: You loop through every entry in revList and get your wanted data structure (that's what Select is doing). x refers to the current entry in the loop, while the stuff to the right side of the arrow is you 'output': a new instance of your profiles class with the members assigned accordingly. The result of all of this is then converted to a list (before ToList(), think of it as a recipe to create the list) and assigned to resas.profiles.
By the way, a word on conventions: Usually, in C#, you would give your classes a name that starts with a capital letter. Also, your profiles class seems to contain data of exactly one profile, so a better name might be Profile. This also makes your data structure more clear, since List<profiles> seems to be a list of lists of profiles - but that's not what it actually is, is it?
Furthermore, Members generally start with a capital letter as well, so instead of action, lastName, you'd have: Action and LastName.
You can try with Linq. This is the code that should solve your issue, but Resas class doesn't have action property:
List<Resas> ls = revList.Select(x => new Resas() {
action = x.todo,
profiles = new List<profiles>() {
new profiles { lastName = x.lastName }
}
).ToList();
If you need to use action property of inprofiles` class:
List<Resas> ls = revList.Select(x => new Resas() {
profiles = new List<profiles>() {
new profiles {
action = x.todo,
lastName = x.lastName
}
}
).ToList();

Want to change JSON Format

I have this class
public class Contact {
#regionContact Info
public Guid ContactID { get; set; }
public string Name { get; set; }
public string RegID { get; set; }
public string MobileNumber { get; set; }
public string Tel { get; set; }
#endregion
}
when I call getAllContact() method, I get this result
[{"ContactID":"7abe6291-43f2-e411-b150-000c2975315f","Name":"Visitor 1","RegID":"1","MobileNumber":"1122334455","Tel":"1122334455"},{"ContactID":"f76f310f-a3f3-e411-b150-000c2975315f","Name":"Visitor 2","RegID":"2","MobileNumber":null,"Tel":null},{"ContactID":"9b3e6018-a3f3-e411-b150-000c2975315f","Name":"Visitor 3","RegID":"3","MobileNumber":null,"Tel":null}]
but what I want is with this kind of format.
{"contacts":[{"ContactID":"7abe6291-43f2-e411-b150-000c2975315f","Name":"Visitor 1","RegID":"1","MobileNumber":"1122334455","Tel":"1122334455"},{"ContactID":"f76f310f-a3f3-e411-b150-000c2975315f","Name":"Visitor 2","RegID":"2","MobileNumber":null,"Tel":null},{"ContactID":"9b3e6018-a3f3-e411-b150-000c2975315f","Name":"Visitor 3","RegID":"3","MobileNumber":null,"Tel":null}]}
How can I change to get this json format? Could anybody help me please?
Your getAllContact() method should an object with one parameter in it called contacts which is of type List
public class ContactList {
public List<Contact> contacts { get; set; }
}
Then serialise the ContactList object.
Try to write like this way . sure u will get your result.Here i have added one item in list. you can add multiple items.
void getAllContact()
{
Dictionary<string, List<Contact>> contactsDic = new Dictionary<string, List<Contact>>();
List<Contact> list = new List<Contact>();
list.Add(new Contact
{
ContactID = Guid.Parse("7abe6291-43f2-e411-b150-000c2975315f"),
Name = "Visitor 1",
RegID = "1",
MobileNumber = "1122334455",
Tel = "1122334455"
}
);
contactsDic.Add("contacts", list);
string ss = JsonConvert.SerializeObject(contactsDic);
}
If your model is Contact class so Simplify do this:
return Ok(new {contacts = yourmodel});

List by GroupBy from IEnumerable

I am trying to create a list of Queues that are displayed by Queue Category. Each Queue Category is assigned an Enum value as such.
public enum QueueCategory
{
None=0,
Critical=1,
High=2,
Orphaned=3,
Missing=4
}
And for each Category, I want to then display these fields.
public class QueueInformation
{
public string Name { get; set; }
public Decimal PercentOfThreshold { get; set; }
public string Host { get; set; }
public DateTime OldestArrival { get; set; }
public QueueCategory Category { get; set; }
}
}
How would I go about linking these two pages so that QueueInformation is displayed by QueueCategory?
IEnumerable<QueueInformation> infos = ...;
foreach (var categoryGroup in infos.GroupBy(i => i.Category))
{
Console.WriteLine("Current category: {0}", categoryGroup.Key);
foreach (var queueInfo in categoryGroup)
{
Console.WriteLine(queueInfo.Name /*...*/);
}
Console.WriteLine("==========================");
}
I assume you want a source ordered by the QueueCategory:
IEnumerable<QueueInformation> list = new BindingList<QueueInformation>();
var orderedList = from l in list orderby l.Category select l;
Hope this helps

Categories

Resources