How to Map Lists in c#? - c#

Hi I am working in c# and I have two list as below
public class Table1
{
public long Id { get; set; }
public int mid {get;set;}
public int ChannelId { get; set; }
public string Header { get; set; }
public string FirstData { get; set; }
public string Type { get; set; }
public string SubType { get; set; }
public string Unit { get; set; }
}
public class Table2
{
public long Id { get; set; }
public int mid {get;set;}
public int ChannelId { get; set; }
public string DateRange { get; set; }
public string Time { get; set; }
}
Below is the final List I want
public class FinalTable
{
public long Id { get; set; }
public int mid {get;set;}
public int ChannelId { get; set; }
public string Header { get; set; }
public string FirstData { get; set; }
public string Type { get; set; }
public string SubType { get; set; }
public string Unit { get; set; }
public List<Table2> table2List { get;set;}
}
So, I have some data in Table1 and Table2. I am retrieving these two lists from different sources and finally I have to prepare list in the form of FinalTable.
In table Table1 for each mid and channelid there will be corresponding values in Table2 also. This is basically one to many relationship where foreach mid and channelid in table1 there will be multiple entries in Table2.
So, after mapping finally I would like to show data in the form of FinalTable. FinalTable has property table2List to accomodate table2 data. I can do this by writing multiple or nested foreach loops but what would be the best approach to solve this.

You can use Linq for this. Your code would look like:
var t1 = new List<Table1>(); // your real data as a list
var t2 = new List<Table2>();
var result = t1.Select(t => new FinalTable {
Id = t.Id,
mid = t.mid,
// ...
table2List = t2.Where(x => x.mid == t.mid && x.ChannelId == t.ChannelId).ToList()
});

Related

Selection for Linq Query

How can I select the List of ExtrasName and ExtrasId in the following query.
The query contains some mathematical operations aswell.
var query =
from a in _context.Cities
from b in a.CityExtras
where a.CityId == CityId && extraIds.Contains(b.ExtrasId)
group new { a, b } by new { a.PricePerSqM , a.Name, a.CityId , } into g
select new
{
City = g.Key.Name,
PricePerSqM = g.Key.PricePerSqM,
TotalPrice = g.Sum(x => x.b.Price) + g.Key.PricePerSqM * squareMeter
};
My Models are:
public class Extras
{
public int ExtrasId { get; set; }
[Required]
public string ExtrasName { get; set; }
public ICollection<CityExtras> CityExtras { get; set; }
}
public class City
{
public int CityId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int PricePerSqM { get; set; }
public ICollection<CityExtras> CityExtras { get; set; }
}
public class CityExtras
{
public int CityId { get; set; }
public City City { get; set; }
public Extras Extras { get; set; }
public int ExtrasId { get; set; }
public int Price { get; set; }
}
I need ExtrasNames and ExtrasId in the query
As they stand, your models are not going to allow you to do this easily. You should add navigation properties to your models, then your Linq will be much cleaner (no need for the double select), and you will be able to navigate upwards to the Extra object and get the data you want.

Asp.net core mvc ViewModel with 2 Models

I'm building a feature with a jquery datatable, the idea is to have a list of stores in the parent row, and then when expanding the parent to list all the licensed terminals in child rows that are linked to the store parent row by a StoreLicenseId column. The issue I am having is that I have a ViewModel with two models, one for the list of stores and one for the licensed terminals. I'm busy building the method into my controller, my problem is in the second part of the method where I new up "StoreLicenseDetails = sl.Select(tl => new TerminalListViewModel()", all the references to tl.terminalId and tl.Terminalname. I get this error "StoreListViewModel does not contain a definition for TerminalID and no accessible extension method". I can see why this is happening, so my question really is, how do I include this "second" TerminalListViewModel into my method to form part of the query ?
ViewModel
public partial class StoreListViewModel
{
public List<TerminalListViewModel> StoreLicenseDetails { get; set; } = null!;
public int Id { get; set; }
public Guid StoreLicenseId { get; set; }
[DisplayName("Store Name")]
public string StoreName { get; set; } = null!;
[DisplayName("App One Licenses")]
public int QtyAppOneLicenses { get; set; }
[DisplayName("App Two Licenses")]
public int QtyAppTwoLicenses { get; set; }
[DisplayName("Date Licensed")]
public DateTime DateLicensed { get; set; }
[DisplayName("Licensed Days")]
public int LicenseDays { get; set; }
[DisplayName("Is License Active")]
public bool LicenseIsActive { get; set; }
}
public partial class TerminalListViewModel
{
public int Id { get; set; }
public Guid StoreLicenseId { get; set; }
public Guid TerminalId { get; set; }
public string TerminalName { get; set; } = null!;
public string LicenseType { get; set; } = null!;
public int TerminalLicenseDays { get; set; }
public DateTime DateLicensed { get; set; }
public bool LicenseIsActive { get; set; }
public bool IsDecommissioned { get; set; }
public DateTime LastLicenseCheck { get; set; }
}
Controller Method
//sl = StoreList
//tl = TerminalList
public IEnumerable<StoreListViewModel> GetStoreList()
{
return GetStoreList().GroupBy(sl => new { sl.StoreLicenseId, sl.StoreName, sl.QtyAppOneLicenses,
sl.QtyAppTwoLicenses, sl.DateLicensed, sl.LicenseDays,
sl.LicenseIsActive })
.Select(sl => new StoreListViewModel()
{
StoreName = sl.Key.StoreName,
QtyAppOneLicenses = sl.Key.QtyAppOneLicenses,
QtyAppTwoLicenses = sl.Key.QtyAppTwoLicenses,
DateLicensed = sl.Key.DateLicensed,
LicenseDays = sl.Key.LicenseDays,
LicenseIsActive = sl.Key.LicenseIsActive,
StoreLicenseId = sl.FirstOrDefault().StoreLicenseId,
StoreLicenseDetails = sl.Select(tl => new TerminalListViewModel()
{
StoreLicenseId = tl.StoreLicenseId,
TerminalId = tl.TerminalId,
TerminalName = tl.TerminalName,
}).ToList()
}).ToList();
}
Based on the error,I suppose your GetStoreList() method returns List<OrderListViewModel> ,but your OrderListViewModel doesn't contains properties of TerminalListViewModel,So you got the error
GetStoreList() method should return List<SourceModel>( Source is the model which contains all the properties of StoreListViewModel and TerminalListViewModel)
For example,the link your provided:Multiple child rows in datatable, data from sql server in asp.net core
public class OrderList
{
//source of properties of OrderListViewModel(parent rows)
public int OrderId { get; set; }
public string Customer { get; set; }
public string OrderDate { get; set; }
//source of properties of OrderListDetailViewModel(child rows)
public int KimlikId { get; set; }
public string Product { get; set; }
public string Color { get; set; }
public int Qntty { get; set; }
}
public class OrderListViewModel
{
public int OrderId { get; set; }
public string Customer { get; set; }
public string OrderDate { get; set; }
public List<OrderListDetailViewModel> OrderListDetails { get; set; }
}
public class OrderListDetailViewModel
{
public int KimlikId { get; set; }
public string Product { get; set; }
public string Color { get; set; }
public int Qntty { get; set; }
}
Orderlist contains all columns OrderListViewModel and OrderListDetailViewModel needs.
When it comes to your case,you should
create 3 models (source,parentrow,childrows)
model for parentrows contains the properties
StoreLicenseId,StoreName, QtyAppOneLicenses,QtyAppTwoLicenses, DateLicensed, LicenseDays,LicenseIsActive
and model for childrows contains the other properties of source model
If you still have questions,please show the data you pulled form db,and I'll write a demo for you

How to join two tables and fetch data from

I have two tables from which I want to fetch the data and return it to the API for consumable purposes. There is a relationship between the two tables.
[![enter image description here][1]][1]
When I try to fetch the data, it is returning only one row which is not what I want.
How can I return all the data related to ResellerId (8435 examples)?
This is my code:
public RateSheetModel GetRateSheet(int resellerId)
{
// This only returns only one row.
// How can I get all rows for all the same Id?
var rateSheetDetails = (from r in _Context.WholesaleRateSheet
where r.ResellerId == resellerId
select r).First();
}
Models
public class WholesaleRateSheetMarkup
{
[Key]
public int RateSheetMarkupId { get; set; }
[Required]
public int ResellerId { get; set; }
[StringLength(50)]
public string RatesheetName { get; set; }
}
public class WholesaleRateSheet
{
[Key]
public int RateSheetId { get; set; }
[Required]
public int RateSheetMarkupId { get; set; }
[Required]
public int ResellerId { get; set; }
public string CountryCode { get; set; }
public string Description { get; set; }
public decimal Peak { get; set; }
public bool IsSouthAfricanRate { get; set; }
public bool IsInertnationRate { get; set; }
public bool IsSpecificRate { get; set; }
public int DestinationGroupSetId { get; set; }
public int DestinationGroupId { get; set; }
public string DestinationLookup { get; set; }
public DateTime CreatedDate { get; set; }
public string CreatedByUsername { get; set; }
public DateTime LastUpdatedDate { get; set; }
public string UpdatedByUsername { get; set; }
}
var rateSheetDetails = (from r in _Context.WholesaleRateSheet
join rateSheet in _Context.<tableName> on r.ResellerId equals rateSheet.ResellerId
where r.ResellerId == resellerId
select new { foo });
You're making a new type by doing this, as a combination of data from both tables. You can either define a model class and use something like
select new MyClass {
Foo = r.RateSheetMarkupId,
Bar = rateSheet.RateSheetName
}
Otherwise, no class definition is required. Simply using 'new' without a class will create an anonymous type with properties that match what you're selecting. The example here could be more precise if you share the entity names.
Altogether, going off your code:
public List<RateSheetModel> GetRateSheet(int resellerId)
{
var rateSheetDetails = (from r in _Context.WholesaleRateSheet
join m in _Context.RateSheetMarkup on r.ResellerId equals m.ResellerId
where r.ResellerId == resellerId
select new RateSheetModel {
ResellerId = r.ResellerId
RatesheetName = m.RatesheetName
};
return rateSheetDetails.ToList<RateSheetModel>;
}
public RateSheetModel { //dunno what this model looks like, but example
public int ResellerId {get; set;}
public string RatesheetName {get; set;}
}

C# creating a relationship between two iLists

I'm trying to fetch a name from one iList into another where they both contain the same ID.
public class Notifications
{
[JsonProperty("note_id")]
public int note_id { get; set;}
[JsonProperty("sender_id")]
public int sender_id { get; set;}
public string sender_name { get; set; }
[JsonProperty("receiver_id")]
public int receiver_id { get; set; }
[JsonProperty("document_id")]
public int document_id { get; set; }
[JsonProperty("search_name")]
public string search_name { get; set; }
[JsonProperty("unread")]
public int unread { get; set; }
}
public class CompanyDirectory
{
[JsonProperty("contact_id")]
public int contact_id { get; set; }
[JsonProperty("first_name")]
public string first_name { get; set; }
[JsonProperty("second_name")]
public string second_name { get; set; }
[JsonProperty("extension")]
public string extension { get; set; }
[JsonProperty("direct_dial")]
public string direct_dial { get; set; }
[JsonProperty("job_title")]
public string job_title { get; set; }
[JsonProperty("company_id")]
public int company_id { get; set; }
}
Then i'm doing the following, the lists both get populated fine. The weird bit is i'm getting errors saying that where I do CompanyDir.first_name that the property doesn't exist, where it clearly does?:
// This occurs just after the class declaration
public IList<Notifications> Notes;
public IList<CompanyDirectory> CompanyDir;
// Ignore that these both use the same string they're created at different parts of the load process
CompanyDir = JsonConvert.DeserializeObject<IList<CompanyDirectory>>(responseString);
Notes = JsonConvert.DeserializeObject<IList<Notifications>>(responseString);
// Now I thought I should be able to do
foreach(var s in Notes){
var thename = CompanyDir.first_name.Where(contact_id.Contains(s.sender_id))
}
You should look up LinQ and Lambda expressions:
var firstNames = CompanyDir.Where(c => c.contact_id == s.sender_id)
.Select(c => c.first_name)
.ToList();
Now you have a list of firstnames. A list, because there may be zero or more hits for your Where constraint.

Accessing properties from multiple classes

I am creating a web application and I have two classes:
public class MOrderMain
{
public int ID { get; set; }
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public DateTime OrderDate { get; set; }
public string BillingName { get; set; }
public string BillingAddress { get; set; }
public string DeliveryName { get; set; }
public string DeliveryAddress { get; set; }
}
public class MOrder
{
public int ID { get; set; }
public int OrhID { get; set; }
public int ProID { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public double Rate { get; set; }
public double Amount { get; set; }
public int DeliveredQty { get; set; }
}
I would like to retrieve details from both classes. For example, I want to get
ID and Billing Name from class MorderMain and all the properties from class MOrder. How can I do this?
I am getting the values by database. I have the query but how will I assign the data and how will I retrieve from both?
var mylist = new List<MOrder>();
_con = _db.GetConnection();
if (_con.State.Equals(ConnectionState.Closed))
{
_con.Open();
}
_cmd = new SqlCommand("Get_All_Order_Details", _con)
{ CommandType = CommandType.StoredProcedure };
_dr = _cmd.ExecuteReader();
while (_dr.Read())
{
mylist.Add(new MOrder
{
ID = Convert.ToInt32(_dr["ordID"]),
OrhID = Convert.ToInt32(_dr["orhID"]),
ProID = Convert.ToInt32(_dr["proID"]),
Name = _dr["pName"].ToString(),
Quantity = Convert.ToInt32(_dr["ordQty"]),
Rate = Convert.ToDouble(_dr["ordRate"]),
Amount = Convert.ToDouble(_dr["ordAmount"]),
DeliveredQty = Convert.ToInt32(_dr["ordQtyDelivered"])
});
}
return mylist;
Since you are retrieving data from both tables in your database but want to combine them in your application, the solution would be to create a single class that contains the data you return from your stored procedure:
public class MAllOrderDetails
{
public int ID { get; set; }
public string BillingName { get; set; }
// include the other billing details you want here
public int OrhID { get; set; }
public int ProID { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public double Rate { get; set; }
public double Amount { get; set; }
public int DeliveredQty { get; set; }
}
Then, your query changes to filling in a List<MAllOrderDetails>.
This leaves your application with only dealing with a collection of a single class with all the data nicely contained in single objects.
var mylist = new List<MAllOrderDetails>();
//...
while (_dr.Read())
{
mylist.Add(new MAllOrderDetails
{
ID = Convert.ToInt32(_dr["ordID"]),
BillingName = _dr["BillingName"].ToString(),
// etc.
OrhID = Convert.ToInt32(_dr["orhID"]),
ProID = Convert.ToInt32(_dr["proID"]),
Name = _dr["pName"].ToString(),
Quantity = Convert.ToInt32(_dr["ordQty"]),
Rate = Convert.ToDouble(_dr["ordRate"]),
Amount = Convert.ToDouble(_dr["ordAmount"]),
DeliveredQty = Convert.ToInt32(_dr["ordQtyDelivered"])
});
}
Update
You could probably get away with this as the closest solution to not creating an additional classes:
class MAllOrderDetails
{
public MOrder Order { get; set; }
public MOrderMain OrderMain { get; set; }
}
I feel, though, that from a maintainability standpoint, this will cause you more headaches than just creating additional classes.

Categories

Resources