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()
});
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;}
}
How to calculate account receivable using LINQ.
I have tried this but stuck here.
I have done this in SQL but I want this in LINQ so I can use it in my MVC project.
var sale = saleslist.GroupBy(s => s.BuyerId).Select(s => s.Sum(u => u.Amount)).ToList();
var receipt = receiptslist.GroupBy(r => r.StakeHolderId).Select(t => t.Sum(u => u.Amount)).ToList();
List<AccountReceivablesVM> res = db.StakeHolders
.Where(r=>r.StakeHolderTypeId == "0b85a69e-55f2-4142-a49d-98e22aa7ca10")
.Select(rvm => new AccountReceivablesVM
{
CompanyName = rvm.CompanyName,
Receivables = //don't know what to do here
}).ToList();
Models:
public class StakeHolder
{
public string StakeHolderId { get; set; }
public string CompanyName { get; set; }
public string Address { get; set; }
public string Contact { get; set; }
public string StakeHolderTypeId { get; set; }
}
public class Sale
{
public string SaleId { get; set; }
public string RefNo { get; set; }
public DateTime Date { get; set; }
public string BuyerId { get; set; }
public string Description { get; set; }
public Nullable<double> Amount { get; set; }
}
public class PaymentsAndReceipt
{
public string PaymentAndReceiptId { get; set; }
public Nullable<int> VoucherNo { get; set; }
public DateTime Date { get; set; }
public string StakeHolderId { get; set; }
public string Description { get; set; }
public Nullable<double> Amount { get; set; }
}
public class AccountReceivablesVM
{
public string CompanyName { get; set; }
public Nullable<double> Receivables { get; set; }
}
Expected Result:
You can join first with stakeholderId and then sum the amount and then group by with company name and stakeholder id, however I write the code in Linq. I have considered the stakeholderid as the primary key of your table just because you have not mentioned the schema of stakeholder so.
var result = from s in db.StakeHolders
join pr in db.PaymentsAndReceipt on s.StakeHolderId equals pr.StakeHolderId
where StakeHolderTypeId == "0b85a69e-55f2-4142-a49d-98e22aa7ca10"
group s by new { s.StakeHolderId,s.CompanyName} into p
select new
{
StakeHolderId= p.Key.StakeHolderId,
CompanyName= p.Key.CompanyName,
Receivables = string.Format("{0:C}", p.Sum(y => y.Amount))
};
I want to query the database and get a sport object containing all inner lists, but for some reason I'm missing, the select only goes 2 levels deep in lists, any deepers and the lists property have a value of null,
example of the structure
public class Sports
{
public int id { get; set; }
public string name { get; set; }
public List<League> leagues { get; set; }
}
public class League
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public List<Team> teams { get; set; }
}
public class Team
{
public int id { get; set; }
public string name { get; set; }
public string successrate { get; set; }
public List<Player> players { get; set; }
}
public class Player
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
}
I created property in MyAppContext file as this
public DbSet<Sports> sports { get; set; }
now when I call an item using select or linq or any other way I tried, the sport object is always 2 Dimensional, meaning it doesn't go deeper than two levels in nested lists! Example of result using var sport=db.Sports.First() the result is {"id":1,"name":"Football","leagues":null} or if I used select()
var sportQuery = db.sports.Select(
s=>new Sports(){
id=s.id,
leagues=s.leagues,
name=s.name
}).First();
I still don't get full information {"id":1,"name":"Football","leagues":[{"id":1,"name":"fc","description":"Some Leauge","teams":null},{"id":2,"name":"al","description":"League","teams":null}]}
why is that! and how to get full object like this
{"id":1,"name":"Football","leagues":[{"id":1,"name":"fc","description":"Some Leauge","teams":[{"id":1,"name":"real madrid","successrate":null,"players":[{"id":1,"name":"Cristiano Ronaldo","age":21},{"id":2,"name":"Iniesta","age":38}]},{"id":2,"name":"Barcelona","successrate":null,"players":[{"id":1,"name":"Cristiano Ronaldo","age":21},{"id":2,"name":"Iniesta","age":38}]}]},{"id":2,"name":"al","description":"League","teams":[{"id":1,"name":"real madrid","successrate":null,"players":[{"id":1,"name":"Cristiano Ronaldo","age":21},{"id":2,"name":"Iniesta","age":38}]},{"id":2,"name":"Barcelona","successrate":null,"players":[{"id":1,"name":"Cristiano Ronaldo","age":21},{"id":2,"name":"Iniesta","age":38}]}]}]}
I've been stuck for days, Please any help would be much appreciated
Try following :
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataBase db = new DataBase();
var sportQuery = db.sports.Select(s=> s.leagues.Select(l => l.teams.Select(t => t.players.Select(p => new {
playerid = p.id,
playerName = p.name,
playerAge = p.age,
teamId = t.id,
teamName = t.name,
teamSucessrate = t.successrate,
leagueId= l.id,
leagueName= l.name,
leagueDescription = l.description,
sportId = s.id,
sportName = s.name
}))
.SelectMany(p => p))
.SelectMany(t => t))
.SelectMany(l => l)
.ToList();
}
}
public class DataBase
{
public List<Sports> sports { get; set;}
}
public class Sports
{
public int id { get; set; }
public string name { get; set; }
public List<League> leagues { get; set; }
}
public class League
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public List<Team> teams { get; set; }
}
public class Team
{
public int id { get; set; }
public string name { get; set; }
public string successrate { get; set; }
public List<Player> players { get; set; }
}
public class Player
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
}
}
problem solved using Include() and thenInclude()
https://learn.microsoft.com/en-us/ef/core/querying/related-data
however, that doesn't explain why Select() only loads one list property deep, also it seems like i should be able to load object with select only or linq
So i have below queries.
I would really like to merge these into 1 query.
Next to the fact that this results in an empty collection (which it shouldn't)
My brain just imploded when i tried making this into 1 query.
So if it's not clear from the code
I want to select all horses from a certain user. that have not been signed up for the race that the user is trying to sign up for.
var userhorses = (from h in entities.Horses
where h.UserId == id
select h);
var race = (from r in entities.Races
where r.Id == id
select r).Single();
var runninghorses = (from rh in race.RacingHorses
where rh.UserId == id
select rh);
var nonracinghorses = (from nrh in userhorses
from rh in runninghorses
where nrh.Id != rh.Id
select nrh).ToList();
EDIT
public class Horse
{
[Key]
public int Id { get; set; }
public int? UserId { get; set; }
public virtual User Owner { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
public int? GenderId { get; set; }
public virtual Gender Gender { get; set; }
public int? ColorId { get; set; }
public virtual Color Color { get; set; }
public int? LegTypeId { get; set; }
public virtual LegType LegType { get; set; }
public int? CharacterId { get; set; }
public virtual Character Character { get; set; }
public int Hearts { get; set; }
public bool Retired { get; set; }
public bool CPU { get; set; }
public bool ForSale { get; set; }
public int ListPrice { get; set; }
public DateTime? Deadline { get; set; }
// Parents
public int? SireId { get; set; }
public virtual Horse Sire { get; set; }
public int? DamId { get; set; }
public virtual Horse Dam { get; set; }
// Internals
public int Stamina { get; set; }
public int Speed { get; set; }
public int Sharp { get; set; }
// Special
public int Dirt { get; set; }
// Externals
public int Start { get; set; }
public int Corner { get; set; }
public int OutOfTheBox { get; set; }
public int Competing { get; set; }
public int Tenacious { get; set; }
public int Spurt { get; set; }
//Future
public virtual ICollection<Race> FutureRaces { get; set; }
//RaceResults
public virtual ICollection<RaceResult> RaceResults { get; set; }
//Training
public virtual ICollection<Training> TrainingResults { get; set; }
//Bids
public virtual ICollection<Bid> Bids { get; set; }
public Horse() {
ForSale = false; //default value
Deadline = null;
}
}
public class Race
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "Purse is required")]
public int Purse { get; set; }
[Required(ErrorMessage = "Slots are required")]
public int Slots { get; set; }
public int SlotPrice { get; set; }
public DateTime? RaceTime { get; set; }
//public int? TrackId { get; set; }
//public virtual Track Track { get; set; }
public int? OwnerId { get; set; }
public virtual User Owner { get; set; }
public virtual ICollection<Horse> RacingHorses { get; set; }
public virtual ICollection<RaceResult> RaceResults { get; set; }
public Race()
{
SlotPrice = 0; //default value
Slots = 8;
}
}
Have you considered using the "let" keyword?
http://msdn.microsoft.com/en-us/library/bb383976.aspx
It also seems you could take benefit of the "except" functionality
http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
(Since I don't have the reputation to make a comment, why are you reusing the variable "id" for both User and identifying a race?)
Additional suggestion is you can filter inside the Single
var race = entities.Races.Single(r => r.Id == raceId);
I am making these assumptions:
you have id, the user ID
you have raceId, the ID of the race being signed up for
there is an entities.RacingHorses collection which is the associations of race and horse IDs
Then you could use:
from h in entities.Horses
where h.UserId == id
let rhs = entities.RacingHorses.Where(rh => rh.HorseId == h.Id)
where !rhs.Any(rh => rh.RaceId == raceId)
select h
Breakdown:
h = a user's horse
rhs = RacingHorses associations for h
if raceId appears in rhs, then h is signed up for that race; do not select this h
all kudo's go to nmclean for this one.
public static SelectList GetNonRacingHorses(int id, int raceId)
{
HorseTracker entities = new HorseTracker();
var race = entities.Races.Single(r => r.Id == raceId);
var racehorses = from h in race.RacingHorses
select h.Id;
var userhorses = (from h in entities.Horses
where
h.UserId == id
orderby h.Name
select h);
var nonracinghorses = from h in userhorses
where !racehorses.Contains(h.Id)
select h;
List<SelectListItem> sli = new List<SelectListItem>();
foreach (Horse horse in nonracinghorses)
{
sli.Add(new SelectListItem { Text = horse.Name, Value = horse.Id.ToString(), Selected = false});
}
return new SelectList(sli, "Value", "Text");
}