appending a collections object - c#

I am working on an existing application that is a package tracking application and I want to append a collections list object.
My code is:
public class VehicleAssignElement
{
public VehicleAssignElement(string pkgID, string DriverID, string VehicleID)
{
pkgID = ConfID;
DriverID = puID;
VehicleID = doID;
}
public string pkgID { get; set; }
public string DriverID { get; set; }
public string VehicleID { get; set; }
}
public class VehicleAssignID
{
public List<VehicleAssignElement> AssignID { get; set; }
}
public class VehicleAssignIDList
{
public List<VehicleAssignID> AssignRecord { get; set; }
}
I have a code block where I loop through to get the pkgID.
assignElement.AssignID.Add( new VehicleAssignElement(oPackageTracking.pkgID,"",""));
I have another code block that I need to loop through to get the DriverID and a 3rd code block to loop the get the VehicleID.
Question:
How would I go about appending the collection to add DriverID as the second element and the VehicleID as the 3rd element?
Using assignElement.AssignID.Add but that adds to the collection. I tried Insert, but was unsuccessful as well.
Any advice is appreciated.

I think you meant something like this:
public class VehicleAssignElement
{
public VehicleAssignElement(string pkgID, string driverID, string vehicleID)
{
this.PkgID = pkgID;
this.DriverID = driverID;
this.VehicleID = vehicleID;
}
public string PkgID { get; set; }
public string DriverID { get; set; }
public string VehicleID { get; set; }
}
public class Form1 : Form
{
private List<VehicleAssignElement> _assignmentList = new List<VehicleAssignElement>();
public void DoSomething()
{
VehicleAssignElement assignment1 = new VehicleAssignElement("pkg1", "John", "Audi");
_assignmentList.Add(assignment1);
VehicleAssignElement assignment2 = new VehicleAssignElement("pkg2", "Morgan", "Volkswagen");
_assignmentList.Add(assignment2);
foreach(var assignment in _assignmentList)
{
Debug.WriteLine(string.Format("{0} -> {1} - {2}", assignment.PkgID, assignment.DriverID, assignment.VehicleID));
}
}
}
NOT TESTED. So it may contain some syntax errors.. But this is for example.

Related

merging two multi level class objects with element update c#

I have two objects (A,B) of same class type (PPLWebOperatorGridList). I need update the A.OldValue with B.Value.
I have tried by adding the guid property and update it in the constructor as shown below. But these object list may repeat same value:
public PPLWebOperatorGridList()
{
this.guid = this.FieldName+this.TagName+
this.Length+this.Encoder+this.Value;
}
public string guid { get; set; }
I have tried as below. I know there are bugs in it but consider the idea in it.
private List<PPLWebOperatorGridList> UpddateOldValues(List<PPLWebOperatorGridList> customeTlvList, List<PPLWebOperatorGridList> customeTlvList2)
{
foreach (var list in customeTlvList)
{
foreach (var list1 in customeTlvList2)
{
if (list.guid == list1.guid)
{
list.OldValue = list1.Value;
if (list.children.Count > 0)
UpddateOldValues(list.children.ToList(), list1.children.ToList());
}
}
}
return customeTlvList;
}
The guid property may be same for some in the list.
class PPLWebOperatorGridList
{
public bool expanded { get; set; }
public string FieldName { get; set; }
public string TagName { get; set; }
public string Length { get; set; }
public string Encoder { get; set; }
public string Value { get; set; }
public List<PPLWebOperatorGridList> children { get; set; }
public string OldValue { get; set; }
}
I need to loop through based on index and update the A.OldValue with B.Value. I am not very familiar with linq, so please suggest a solution.

How to change constructor of a class to recieve generic list of objects of already created class and constructor? (C#)

I have the following class:
public class OrderArticlesAdapter : RecyclerView.Adapter
{
public List<OrderArticleViewModel> listOfOrderArticles;
.....
.....
//constructor
public OrderArticlesAdapter(List<OrderArticleViewModel> orderArticles, ....., .....)
{
listOfOrderArticles = orderArticles;
......
}
}
I want the class to be able to work not only with list of OrderArticleViewModel but also with list of type Invoices and any other type. OrderArticleViewModel class looks like that:
public class OrderArticleViewModel
{
public string ArticleId { get; set; }
public string LotId { get; set; }
public string ArticleName { get; set; }
public string PriceDiscount { get; set; }
public string ArticlePrice { get; set; }
public string ArticleQuantity { get; set; }
public string ArticleTotalPrice { get; set; }
public string Barcode { get; set; }
public string ExpireDate { get; set; }
public string LotName { get; set; }
public string ArticlePriceAfterDiscount
{
get
{
decimal priceDiscount;
if (!Decimal.TryParse(PriceDiscount, out priceDiscount))
{
priceDiscount = 0;
}
decimal articlePrice = Convert.ToDecimal(ArticlePrice);
decimal discountAmount = Math.Round(articlePrice * (priceDiscount / 100), 4);
decimal articlePriceAfterDiscount = articlePrice - discountAmount;
return articlePriceAfterDiscount.ToString();
}
}
}
Invoices class looks like that:
public class Invoices
{
public string ArtId { get; set; }
public string Name { get; set; }
public string Quantity { get; set; }
public string Price { get; set; }
public string Sum { get; set; }
public string Discount { get; set; }
public string PriceWodiscount { get; set; }
public string Id { get; set; }
}
ArticleId , ArticleName, ArticleQuantity, PriceDiscount, ArticlePrice, Discount, ArticlePriceAfterDiscount from class OrderArticleViewModel correspond to properties ArtId, Name, Quantity, Discount, Price, Sum from class Invoices. How do I make OrderArticlesAdapter constructor to be able to recieve generic list of OrderArticleViewModel or Invoices or any other type without breaking the functionality of the code where I already have used instance of OrderArticlesAdapter?
Create another constructor in which you convert the invoice list to an ArticleViewModel list:
public class OrderArticlesAdapter : RecyclerView.Adapter
{
public List<OrderArticleViewModel> listOfOrderArticles;
public OrderArticlesAdapter(List<OrderArticleViewModel> orderArticles, ....., .....)
{
listOfOrderArticles = orderArticles;
}
public OrderArticlesAdapter(List<Invoice> invoices)
{
listOfOrderArticles = invoices.Select(MapToArticleVM).ToList();
}
private OrderArticleViewModel MapToArticleVM(Invoice invoice)
{
return new OrderArticleViewModel
{
ArticleId = invoice.ArtId,
// ...
};
}
}
Do note the resulting list will miss some properties, because Invoice doesn't contain Barcode, for example.
One option would be to write an extension method to convert an invoice to view model
public static class InvoicesExtensions
{
public static OrderArticleViewModel ToOrderArticleViewModel(this Invoices i)
{
return new OrderArticleViewModel { ArticleId = i.ArtId, ... };
}
}
... and then you can call the constructor like
var invoices = new List<Invoices>();
var adapter = new OrderArticlesAdapter(invoices.Select(i => i.ToOrderArticleViewModel()).ToList());
I would also recommend
renaming Invoices to Invoice as it seems to represent an actual invoice not multiple invoices
use IEnumerable<OrderArticleViewModel> instead of List<OrderArticleViewModel> for the constructor parameter as this makes the constructor more versatile

AutoMapper returns NULL when returning a list

Code without AutoMapper:
List<CountryDM> countryDMList = _countryRepo.GetCountry();
List<CountryVM> countryVMList = new List<CountryVM>();
foreach (CountryDM countryDM in countryDMList)
{
countryVMList.Add(CountryVM.ToViewModel(countryDM));
}
return countryVMList;
I used AutoMapper for the above task. But it returns a NULL list. Please refer the below code:
List<CountryDM> countryDMList = _countryRepo.GetCountry();
Mapper.CreateMap<List<CountryDM>, List<CountryVM>>();
List<CountryVM> countryVMList = new List<CountryVM>();
return Mapper.Map<List<CountryVM>>(countryDMList);
public class CountryDM
{
public int ID { get; set; }
public string CountryCode { get; set; }
public string Description { get; set; }
}
public class CountryVM
{
public int ID { get; set; }
public string CountryCode { get; set; }
public string Description { get; set; }
}
You don't need to define a mapping between lists, just between objects, AutoMapper will know how to extrapolate that:
Mapper.CreateMap<CountryDM, CountryVM>();
the rest stays the same

C# Accessing a methods value dynamically using a string

I am currently setting some strings via this method:
string marketlabel = allmarketdata.#return.markets.COLXPM.label.ToString();
I would like to set the market label dynamically by having a string for the actual market choice.
string currentMarketSelected= this.marketTextBox.Text; // Specific market: COLXPM
string marketlabel=allmarketdata.#return.markets.currentMarketSelected.label.ToString();
I have been searching for a few hours and probably am not explaining correctly. I tried some stuff with reflections with no success. Basically what I want to do is have a textbox or list which contains all the market names and based on which one is selected start setting the data.
Above is the best type of example of what I want to do even though it is not syntactically possible to use a variable in place.
public class Markets
{
public COLXPM COLXPM { get; set; }
//Lots of markets below here
}
public class COLXPM
{
public string marketid { get; set; }
public string label { get; set; }
public string lasttradeprice { get; set; }
public string volume { get; set; }
public string lasttradetime { get; set; }
public string primaryname { get; set; }
public string primarycode { get; set; }
public string secondaryname { get; set; }
public string secondarycode { get; set; }
public List<Recenttrade> recenttrades { get; set; }
public List<Sellorder> sellorders { get; set; }
public List<Buyorder> buyorders { get; set; }
}
public class Return
{
public Markets markets { get; set; }
}
public class RootObject
{
public int success { get; set; }
public Return #return { get; set; }
}
The proposed solution below that worked
string currentMarketSelected = "DOGEBTC"; // Just selecting one of the markets to test it works
var property = allmarketdata.#return.markets.GetType().GetProperty(currentMarketSelected);
dynamic market = property.GetMethod.Invoke(allmarketdata.#return.markets, null);
string marketlabel = market.label.ToString(); //Gets all my selected market data
Here is a solution using reflection.
string currentMarketSelected= this.marketTextBox.Text; // Specific market: COLXPM
var property = allmarketdata.#return.markets.GetType().GetProperty(currentMarketSelected);
dynamic market = property.GetGetMethod().Invoke(allmarketdata.#return.markets, null);
string marketlabel=market.label.ToString();
You need something like this:
public class Markets
{
public COLXPM this[string key]
{
get
{
COLXPM colxpm;
switch (key)
{
// TODO : use "key" to select instance of COLXPM;
case "example1":
colxpm = ...;
break;
default:
throw new NotSupportedException();
}
return colxpm;
}
}
}
Then you can do something like:
string marketlabel=allmarketdata.#return.markets[currentMarketSelected]label.ToString();
This is an indexed property.

Updating List<T> in DbContext

I have a Model like this
public class Challenge
{
public int ID { get; set; }
public string Name { get; set; }
public string Blurb { get; set; }
public int Points { get; set; }
public string Category { get; set; }
public string Flag { get; set; }
public List<string> SolvedBy { get; set; }
}
public class ChallengeDBContext : DbContext
{
public DbSet<Challenge> Challenges { get; set; }
}
and then Controller like this. But I cannot update the List "SolvedBy", the next time I step through with the debugger, the list is still empty.
[HttpPost]
public string Index(string flag = "", int id=0)
{
Challenge challenge = db.Challenges.Find(id);
if (flag == challenge.Flag)
{
var chall = db.Challenges.Find(id);
if (chall.SolvedBy == null)
{
chall.SolvedBy = new List<string>();
}
chall.SolvedBy.Add(User.Identity.Name);
db.Entry(chall).State = EntityState.Modified;
db.SaveChanges();
//congrats, you solved the puzzle
return "got it";
}
else
{
return "fail";
}
}
is there any way around it to make a list of strings kept in the database?
EF don't know how to store an array in database table so it just ignore it. You can create another table/entity or use XML/JSON to store the list. You can serialize the list before saving and deserialize it after loading from database
A List<T> in a model would normally map to a second table, but in your DbContext you only have a single table. Try adding a second table.
public class ChallengeDBContext : DbContext
{
public DbSet<Challenge> Challenges { get; set; }
public DbSet<Solution> Solutions {get; set;}
}
public class Challenge
{
public int ID { get; set; }
public string Name { get; set; }
public string Blurb { get; set; }
public int Points { get; set; }
public string Category { get; set; }
public string Flag { get; set; }
public List<Solution> SolvedBy { get; set; }
}
public class Solution
{
public int ID { get; set; }
public string Name { get; set; }
}
Then your controller can use code along the lines of...
var chall = db.Challenges.Find(id);
if (chall.SolvedBy == null)
{
chall.SolvedBy = new List<Solution>();
}
chall.SolvedBy.Add(new Solution {Name=User.Identity.Name});
None of the above has been tested and I may have made some mistakes there, but the general principle I want to illustrate is the fact that you need another table. The List<T> represents a JOIN in SQL.

Categories

Resources