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.
Related
I have a list of objects like this
public class MyList
{
public int recordNo { get; set; }
public bool IsValid { get; set; }
}
var result= (from pool in context.Table.Where(prdicate)
select new ResultEntity
{
guid = pool.guid,
isValid = myList.FirstOrDefault(no => no.guid == pool.guid).IsValid //It thorws an error here
}
the error is
System.NotSupportedException:
the error caused because IsValid assign
So I want to join the list with a table, to asssign some values on it. How can I do that?
Customer customerAlias = null;
Organization organizationAlias = null;
IList<Customer> customers = session.QueryOver(() => customerAlias)
.Left.JoinAlias(x => x.Organization, () => organizationAlias)
.Where(customer => customer.Name == "Customer Name")
.And(() => customerAlias.Age > 18)
.AndNot(() => organizationAlias.Name == "Forbidden Organization")
.List();
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; }
}
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;
}
Several time, i need to get the name of user in AplicationUsers (aspnetusers). Like in Chamado model (table) i have a column Id_Agente (user). With a simple List, i will get something like:
"3q0aju9-9ijuso-9sodkci..."
public class Chamado
{
public int Id { get; set; }
public DateTime Abertura { get; set; }
public string Titulo { get; set; }
public string Descricao { get; set; }
public string Id_Agente { get; set; }
[NotMapped]
public String NomeAgente { get; set; }
}
To work around, I created a NotMapped field and filled it with a foreach:
using (IdentityContext id2 = new IdentityContext())
{
foreach (var item in historicos)
{
item.NomeAgente = id2.Users
.Where(u => u.Id == item.Id_Agente)
.Select(u => u.Nome).FirstOrDefault();
}
}
But now I need to group Chamados by Agente, and it's becoming more and more harder, to work around. I tried to make another notMapped on chamados model named Qtde, make a list and extract from that list but returned a error:
public List<PainelChamados> ListarOrdem()
{
using (SistemaContext db = new SistemaContext())
{
var chamados = db.Chamado
.Where(c => c.Situacao != Chamado.Esituacao.Concluido)
.GroupBy(c => c.Id_Agente)
.Select(c => new Chamado { Id_Agente = c.Key, Qtde = c.Count() });
using (IdentityContext id2 = new IdentityContext())
{
foreach (var item in chamados)
{
item.NomeAgente = id2.Users
.Where(u => u.Id == item.Id_Agente)
.Select(u => u.Nome).FirstOrDefault();
}
}
var query = chamados
.Select(c => new PainelChamados
{
Agente = c.NomeAgente,
Qtde = c.Qtde
});
return query.ToList();
}
}
Last, but not least, how could I just Include aspnetusers table like another regular table:
var query = db.Suporte_Projeto
.Include(l => l.Licenciado)
.Include(c => c.Condominio)
.Include(pr => pr.ProjetoProduto)
.Include(p => p.ProjetoAcesso);
Chart Data
Error
I did another work around! It's seems to be a good option while i cant join aspnetusers to my models table:
public List<PainelChamados> ListarOrdem()
{
using (SistemaContext db = new SistemaContext())
{
var query = db.Chamado
.Where(c => (c.Situacao != Chamado.Esituacao.Concluido && c.Id_Agente != null))
.GroupBy(e => new { e.Id_Agente})
.Select(lg => new PainelChamados
{
CodAgente = lg.Key.Id_Agente,
Qtde = lg.Count()
});
UsuarioData ud = new UsuarioData();
List<PainelChamados> Lista = new List<PainelChamados>();
foreach (var item in query)
{
Lista.Add(new PainelChamados
{
CodAgente = item.CodAgente,
Agente = item.CodAgente == null ? string.Empty : ud.GetAgenteId(item.CodAgente),
Qtde = item.Qtde
});
}
return Lista;
}
}
What do you think, is it the best way to work around? I could return the list i desired.
Chart With Agente Names
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");