select multiple fields in join - c#

I am trying to group by magnitudId and return an anonymous type containing fields MagnitudID, CalibracionID and MaxDate in order to then join by calibracionVerificacionId but below linq query is not working:
(from c in equipo.CalibracionVerificacion
join c2 in
(from c3 in equipo.CalibracionVerificacion
where c3.equipoId == equipo.equipoId && !(c3.magnitudId == null || c3.magnitudId.Trim() == string.Empty)
group c3 by c3.magnitudId into cgroup
select new
{
MagnitudID = cgroup.Key,
CalibracionID = cgroup.Select(x => x.calibracionVerificacionId),
MaxDate = cgroup.Max(x => x.fechaPrevista),
}
) on c.calibracionVerificacionId equals c2.CalibracionID
where c.equipoId == equipo.equipoId
select c).Min(d => d.fechaPrevista);

It is not clear what you are asking. It looks like you're joining the same list on itself, then grouping and then selecting the min of the max date?
If so, maybe this will work for you:
void Main()
{
var CalibracionVerificacion = new List<Equipo>();
var results = CalibracionVerificacion
.Join(
CalibracionVerificacion.Where(x => !String.IsNullOrWhiteSpace(x.magnitudId)),
c1 => c1.equipoId,
c2 => c2.equipoId,
(c1, c2) => new {c1, c2})
.GroupBy(x => x.c2.magnitudId)
.Select(g => new
{
MagnitudID = g.Key,
CalibracionID = g.Select(x => x.c1.calibracionVerificacionId),
MaxDate = g.Max(x => x.c1.fechaPrevista)
})
.Min(g => g.MaxDate);
}
class Equipo {
public int equipoId { get; set; }
public string magnitudId { get; set; }
public int calibracionVerificacionId { get; set; }
public int fechaPrevista { get; set; }
}

Related

IQueryable<T> on mongoDB '$project or $group does not support {document}

I am getting this issue after running Select on IQueryable
'$project or $group does not support {document}.'
public Interface IVideo
{
....
public string File { get; set;}
public bool Categorized { get; set;}
public IMovie Movie { get; set;}
....
}
public Interface IMovie
{
....
public List<string> Langauge {get; set;}
....
}
public static Dictionary<string, int> GetLanguage(string isp)
{
//Repository.GetVideos() is IQueryable<IVideo>
var videos = Repository.GetVideos().Where(q => q.Categorized && (
q.File == isp ||
q.File == "st"));
var language = videos.SelectMany(q => q.Movie.Language).Select(e => e);
var ql = from x in language
group x by x
into g
let count = g.Count()
orderby count descending
select new {g.Key, count}; // issue is here
return ql.ToDictionary(item => item.Key, item => item.count);
}
How can I fix this issue?
Found the Fix
As MongoDB does not support grouping or projection just ToList the language available
public static Dictionary<string, int> GetLanguage(string isp)
{
//Repository.GetVideos() is IQueryable<IVideo>
var videos = Repository.GetVideos().Where(q => q.Categorized && (
q.File == isp ||
q.File == "st"));
//ToList() added here
var language = videos.SelectMany(q => q.Movie.Language).Select(e => e).ToList();
var ql = from x in language
group x by x
into g
let count = g.Count()
orderby count descending
select new {g.Key, count};
return ql.ToDictionary(item => item.Key, item => item.count);
}

Linq complex Inner Join

I want to join my data with linq inner join as:
[DataContract]
public class Data
{
[DataMember(Order = 0, IsRequired = false, EmitDefaultValue = false)]
public List<DataResultObject> Row { get; set; }
}
[DataContract]
public class DataResultObject
{
[DataMember]
public string NAME { get; set; }
[DataMember]
public string VALUE { get; set; }
[DataMember]
public string TYPE { get; set; }
}
List<Data> follow = (List<Data>)dataset_cache.Get("follow");//364 rows
List<Data> icerik = (List<Data>)dataset_cache.Get("icerik");//134854 rows
List<Data> follow_icerik = icerik.Join(follow,
i => i.Row.Where(w => w.NAME == "CrawlSourceId").Select(s => s.VALUE),
f => f.Row.Where(w => w.NAME == "crawl_source_id").Select(s => s.VALUE),
(i, f) =>
new Data
{
Row = i.Row.Concat(nf.Row).ToList()
}
).Take(5).ToList();
But it returns empty, how to use inner join when we have list in "on" clause ?
Try this:
List<Data> follow_icerik = icerik.Concat(
icerik.SelectMany(e => e.Row)
.Where(w => w.NAME == "CrawlSourceId")
.Join(follow.SelectMany(e => e.Row)
.Where(w => w.NAME == "crawl_source_id"),
i => i.VALUE,
f => f.VALUE,
(i, f) =>
new List<DataResultObject> { i, f }
).Select(e => new Data { Row = e })
).ToList();
EDIT:
icerik.SelectMany(e=>e.Row) - select rows with data which we are needed
icerik.SelectMany(e=>e.Row).Where(w => w.NAME == "CrawlSourceId") - filter this data
... Join(... - join filtered data
In Join we also have to filter data before join: follow.SelectMany(e=>e.Row) .Where(w => w.NAME == "crawl_source_id")
i => i.VALUE,
f => f.VALUE, - fields on which we join data.

How to OrderBy nested Object value Linq

Object
namespace Example
{
public class ContractorAddValue
{
public Member Member { get; set; }
public List<Addresses> Addresses { get; set; }
public ICommand AddAddress { get; set; }
}
public class Addresses
{
public MemberAddress MemberAddress { get; set; }
public ICommand EditAddress { get; set; }
}
}
Query
public ObservableCollection<ContractorAddValue> GetContractorsOrderByCity()
{
var allContractors = (from c in db.Member where c.IsContrator == true select c).ToList();
//var allContractors2 = db.Member .Include(c => c.MemberAddress).SelectMany(c => c.MemberAddress).OrderBy(c => c.City).Select(c => c.Member ).ToList();
//var allContractors = (from c in db.Member where c.IsContrator == true select c).OrderBy(c => c.MemberAddress.OrderBy(x => x.City)).ToList(); <= dosent work
var listContractorAddValue = new ObservableCollection<ContractorAddValue>();
foreach (var i in allContractors)
{
var adressList = db.MemberAddress.Where(x => x.MemberId == i.MemberId).OrderBy(x => x.City).ToList();
ContractorAddValue contractorAddValue = new ContractorAddValue();
contractorAddValue.Member = i;
contractorAddValue.AddAddress = new BaseCommand(() => ContractorsViewModel.SendAddress(i.MemberId ));
contractorAddValue.Addresses = new List<Addresses>();
foreach (var a in adressList)
{
Addresses memberAdress = new Addresses();
memberAdress.MemberAddress = a;
memberAdress.EditAddress = new BaseCommand(() => ContractorsViewModel.SendEditAddress(a.MemberAddressId , i.MemberId ));
contractorAddValue.Addresses.Add(memberAdress);
}
listContractorAddValue.Add(contractorAddValue);
}
return listContractorAddValue;
}
allContractors2 - the order by works, but I retrieve repeating Members. In this approach I tried to use .Distinct() after Select(c => c.Member) but it doesn't work (the whole query stops working).
My goal is to make an order by MemberAddress.City
Thanks in advance!
I think that this code will work but you need to redefine the Equals method of the ContractorAddValue class.
I added one if statement when you want to add contractorAddValue to the list. First you need to check if your list contains that object. If not you add the object to the list. If yes you need to find that object and merge its addresses list with addresses list from the object you want to add.
public ObservableCollection<ContractorAddValue> GetContractorsOrderByCity()
{
var allContractors = (from c in db.Member where c.IsContrator == true select c).ToList();
//var allContractors2 = db.Member .Include(c => c.MemberAddress).SelectMany(c => c.MemberAddress).OrderBy(c => c.City).Select(c => c.Member ).ToList();
//var allContractors = (from c in db.Member where c.IsContrator == true select c).OrderBy(c => c.MemberAddress.OrderBy(x => x.City)).ToList(); <= dosent work
var listContractorAddValue = new ObservableCollection<ContractorAddValue>();
foreach (var i in allContractors)
{
var adressList = db.MemberAddress.Where(x => x.MemberId == i.MemberId).OrderBy(x => x.City).ToList();
ContractorAddValue contractorAddValue = new ContractorAddValue();
contractorAddValue.Member = i;
contractorAddValue.AddAddress = new BaseCommand(() => ContractorsViewModel.SendAddress(i.MemberId ));
contractorAddValue.Addresses = new List<Addresses>();
foreach (var a in adressList)
{
Addresses memberAdress = new Addresses();
memberAdress.MemberAddress = a;
memberAdress.EditAddress = new BaseCommand(() => ContractorsViewModel.SendEditAddress(a.MemberAddressId , i.MemberId ));
contractorAddValue.Addresses.Add(memberAdress);
}
if(!listContractorAddValue.Contains(contractorAddValue)){
listContractorAddValue.Add(contractorAddValue);
} else {
var contAddValue = listContractorAddValue.First(l => l.Equals( contractorAddValue));
contAddValue.Addresses.AddRange(contractorAddValue.Addresses);
}
}
return listContractorAddValue;
}

ASP.NET MVC 5 Entity Join

I'm new in ASP, Entity and lambda expressions. How can I join two tables?
Route Model:
public partial class Route
{
public Route()
{
Flights = new HashSet<Flight>();
}
public int RouteID { get; set; }
public int DepartureAirportID { get; set; }
public int ArrivalAirportID { get; set; }
public int FlightDuration { get; set; }
public virtual Airport Airport { get; set; }
public virtual Airport Airport1 { get; set; }
public virtual ICollection<Flight> Flights { get; set; }
}
Airport Model:
public partial class Airport
{
public Airport()
{
Routes = new HashSet<Route>();
Routes1 = new HashSet<Route>();
}
public int AirportID { get; set; }
public string City { get; set; }
public string Code { get; set; }
public virtual ICollection<Route> Routes { get; set; }
public virtual ICollection<Route> Routes1 { get; set; }
}
SQL query looks like this:
SELECT a.AirportID, a.City
FROM Route r INNER JOIN Airport a ON r.ArrivalAirportID = a.AirportID
WHERE r.DepartureAirportID = #departureAirportID
ORDER BY a.City
Sorry for this easy question but I don't know how to do this with Entity Framework...
Something like this should do (untested and just going on from your query) with a variable hard-coded):
using (var db = new YourDbContext())
{
var query = from r in db.Route
join a in db.Airport a on r.ArrivalAirportID equals a.AirportID
where r.DepartureAirportID = 1 // replace with your varialble.
orderby a.City
select a;
}
Include with join entity framework. here doctorSendAnswerModel also a inner table.
var data = _patientaskquestionRepository.Table.Include(x=>x.DoctorSendAnswer).Join(_patientRepository.Table, a => a.PatientId, d => d.Id, (a, d) => new { d = d, a = a }).Where(x => x.a.DoctorId == doctorid);
if(!string.IsNullOrEmpty(status))
data=data.Where(x=>x.a.Status==status);
var result = data.Select(x => new {x= x.a,y=x.d }).ToList();
var dt = result.Select(x => new PatientAskQuestionModel()
{
PatientId = x.x.PatientId.Value,
AskQuestion = x.x.AskQuestion,
Id = x.x.Id,
DoctorId = x.x.DoctorId,
FileAttachment1Url = x.x.FileAttachment1,
DocName = x.y.FirstName + " " + x.y.LastName,
CreatedDate = x.x.CreatedDate.Value,
doctorSendAnswerModel = x.x.DoctorSendAnswer.Select(t => new DoctorSendAnswerModel { Answer = t.Answer }).ToList()
}).ToList();
return dt;
LinQ query:
from r in context.Route
join a in context.Airport
on r.ArrivalAirportID equals a.AirportID
WHERE r.DepartureAirportID = "value"
ORDER BY a.City
select a.AirportID, a.City
var balance = (from a in context.Airport
join c in context.Route on a.ArrivalAirportID equals c.AirportID
where c.DepartureAirportID == #departureAirportID
select a.AirportID)
.SingleOrDefault();
You can do the following:
var matches = from a in context.Airports
join r in context.Routes
on a.AirportID equals r.ArrivalAirportID
where r.DepartureAirportID = departureAirportID
order by a.City
select new
{
a.AirportID,
a.City
};
Entity query with conditional join with pagination.
if (pageIndex <= 0)
pageIndex = 1;
pageIndex = ((pageIndex - 1) * pageSize) ;
var patient = _patientRepository.Table.Join(_DoctorPatient.Table.Where(x => x.DoctorId == Id && x.IsBlocked==false), x => x.Id, d => d.PatientId, (x, d) => new { x = x });
if (state != "")
patient = patient.Where(x => x.x.State.Contains(state));
if (name != "")
patient = patient.Where(x => (x.x.FirstName + x.x.LastName).Contains(name));
if (sdate != null)
patient = patient.Where(x => x.x.CreatedDate >= sdate);
if (eDate != null)
patient = patient.Where(x => x.x.CreatedDate <= eDate);
var result = patient.Select(x => x.x).Select(x => new PatientDoctorVM() { PatientId = x.Id, Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, SSN = x.NewSSNNo, UserProfileId = x.UserProfileId, Email = x.Email, TumbImagePath = x.TumbImagePath }).OrderBy(x => x.Id).Skip(pageIndex).Take(pageSize).ToList();
Your entity and lembda query will be lool like this:
return (from d in _doctorRepository.Table
join p in _patientDoctor.Table on d.Id equals p.DoctorId
where p.PatientId == patientid.Value select d
).ToList();
Take a look at this site, it will explain you how the join works in Linq.
So if you ever need it again you will be able to solve it yourself.

How to write Lambda expression for this SQL query?

I have the following SQL query
Select cLedgerName,dDateFrom,cPeriodType,nPeriodFrom,nPeriodTo
from sys_Account_Ledger a,sys_Log_Deposits_Interest_Master b
where a.cGLCode=b.cGLCode and b.dDateFrom='08-11-2012' and b.cPeriodType='Days'
I wanted to write this query using Lambda expression.This is where I am stuck.
public IList<ListViewData> GetDepositsListViewData(string glCode, string effectDate, string periodType)
{
using (var db = new DataClasses1DataContext())
{
var data=db.sys_Account_Ledgers.Join(db.sys_Log_Deposits_Interest_Masters,
ledger=>ledger.cGLCode,
deposits=>deposits.cGLCode,
(ledger,deposits)=>new {db.sys_Account_Ledgers =ledger,db.sys_Log_Deposits_Interest_Masters =deposits})
}
}
I have created a class which will be the return type of my query.
Here is the class
public class ListViewData
{
public string LedgerName { get; set; }
public string DateFrom { get; set; }
public string PeriodType { get; set; }
public int PeriodFrom { get; set; }
public int PeriodTo { get; set; }
}
Can anyone help me out with the lambda expression?
var result = dataContext.SysAccountLedger
.Join(dataContext.SysLogDepositsInterestMaster,
a => a.cGlCode,
b => b.cGlCode,
(a, b) => new ListViewData
{
LedgerName = a.LedgerName,
DateFrom = b.DateFrom,
PeriodType = b.PeriodType
// other properties
})
.Where(item => item.DateFrom = Convert.ToDateTime("08-11-2012") &&
item.PeriodType == "Days")
.ToList();
//Direct translation into Linq:
var query = from a in db.sys_Account_Ledger
join b in db.sys_Log_Deposits_Interest_Master on a.cGLCode equals b.cGLCode
where b.dDateFrom == Convert.ToDateTime("08-11-2012") && b.cPeriodType == "Days"
select new { a, b };
//Lambda of this:
var query = db.sys_AccountLedger
.Join(db.sys_Log_Deposits_Interest_Master,
a => a.cGLCode,
b => b.cGLCode,
(a, b) => new {a , b})
.Where(w => w.dDateFrom == Convert.ToDateTime("08-11-2012") && w.cPeriodType == "Days");

Categories