I have a counterpart, which has an address, which MIGHT have a country assigned.
How do I handle this:
InvoiceAddress invoiceAddres = null;
Country InvoiceAddressCountry = null;
Counterpart counterpart = null;
CounterpartTabDTO result = null;
// projections for DTO-mapping
var projections = new[]
{
Projections.Property(() => counterpart.CounterpartId).WithAlias(() => result.InternalID),
Projections.Property(() => counterpart.GlobalCounterpartId).WithAlias(() => result.BasicInfo_GlobalCounterpartyID),
Projections.Property(() => counterpart.Name).WithAlias(() => result.BasicInfo_Name),
Projections.Property(() => counterpart.ShortName).WithAlias(() => result.BasicInfo_ShortName),
Projections.Property(() => counterpart.PhoneNumber).WithAlias(() => result.BasicInfo_Telephone),
Projections.Property(() => counterpart.Webpage).WithAlias(() => result.BasicInfo_WWW),
Projections.Property(() => counterpart.Language).WithAlias(() => result.BasicInfo_Language),
Projections.Property(() => counterpart.VAT).WithAlias(() => result.BasicInfo_VAT),
Projections.Property(() => counterpart.CompanyRegistrationNumber).WithAlias(() => result.BasicInfo_CompanyRegistationno),
Projections.Property(() => invoiceAddres.Name).WithAlias(() => result.BasicInfo_InvoiceAddressContactPerson),
Projections.Property(() => invoiceAddres.Street).WithAlias(() => result.BasicInfo_InvoiceAddressAddress),
Projections.Property(() => invoiceAddres.PostalCode).WithAlias(() => result.BasicInfo_InvoiceAddressPostalCode),
Projections.Property(() => invoiceAddres.City).WithAlias(() => result.BasicInfo_InvoiceAddressCity),
Projections.Property(() => invoiceAddres.Area).WithAlias(() => result.BasicInfo_InvoiceAddressArea),
Projections.Property(() => InvoiceAddressCountry.PrintableName).WithAlias(() => result.BasicInfo_InvoiceAddressCountry),
Projections.Property(() => invoiceAddres.Department).WithAlias(() => result.BasicInfo_InvoiceAddressDepartment),
Projections.Property(() => invoiceAddres.Fax).WithAlias(() => result.BasicInfo_InvoiceAddressFax),
Projections.Property(() => invoiceAddres.MainEmail).WithAlias(() => result.BasicInfo_InvoiceAddressEmail),
};
var query = Session.QueryOver(() => counterpart)
.JoinQueryOver<InvoiceAddress>(x => x.InvoiceAddresses, () => invoiceAddres)
.Where(x => x.IsDefault)
.JoinQueryOver<Country>(() => invoiceAddres.Country, () => InvoiceAddressCountry)
.Select(projections);
The issue is InvoiceAddressCountry, which might be null. If that happens, I'd like the result.BasicInfo_InvoiceAddressCountry property stays null.
To clarify, the above code does not work. It can't handle the null.
From your words I can suppose that you'll need to use left join:
.Left.JoinQueryOver(() => invoiceAddres.Country, () => InvoiceAddressCountry)
Related
I have a scenario where in case there is a specific boolean value satisfied (office_debit_total line) I can get amount directly from a column otherwise I need to calculate it by grouping some specific values, here's the code:
var result = products.Select(p => new ResponseDto()
{
customer_id = p.CustomerId,
office_debit_date = p.OfficeDebitDate.Value.ToString(),
office_debit_id = p.OfficeDebitId.ToString(),
office_debit_total = p.OfficeEnum == SomeEnum.ValueType ? p.OfficeAmount.ToString() : totalAmounts[p.OfficeDebitId].ToString(),
payment_method = p.PaymentMethod.Value.ToString(),
}).ToList();
As it's possible to be seen office_debit_total is calculated depending on enum value, and here's dictionary that I'm using to get grouped data:
Dictionary<string, decimal> totalAmounts = products
.Where(p => p.ProductType == ProductType.ValueType)
.GroupBy(p => new { p.OfficeDebitId, p.OfficeDebitDate, p.PaymentMethod })
.ToDictionary(x => x.Key.OfficeDebitId, x => x.Sum(p => p.Amount));
But I have receiving following error message:
An item with the same key has already been added.
I've tried writing .ToLookup instead of .ToDictionary but that didn't helped me..
Thanks guys
Cheers
If your dictionary has only OfficeDebitId as key then you need to group by only by it:
var totalAmounts = products
.Where(p => p.ProductType == ProductType.ValueType)
.GroupBy(p => p.OfficeDebitId)
.ToDictionary(x => x.Key, x => x.Sum(p => p.Amount));
or use full anonymous object as key:
var totalAmounts = products
.Where(p => p.ProductType == ProductType.ValueType)
.GroupBy(p => new { p.OfficeDebitId, p.OfficeDebitDate, p.PaymentMethod })
.ToDictionary(x => x.Key, x => x.Sum(p => p.Amount));
Or with value tuple as key:
var totalAmounts = products
.Where(p => p.ProductType == ProductType.ValueType)
.GroupBy(p => (p.OfficeDebitId, p.OfficeDebitDate, p.PaymentMethod))
.ToDictionary(x => x.Key, x => x.Sum(p => p.Amount));
Why not this:
Dictionary<string, decimal> totalAmounts = products
.Where(p => p.ProductType == ProductType.ValueType)
.GroupBy(p => p.OfficeDebitId)
.ToDictionary(x => x.Key, x => x.Sum(p => p.Amount));
You might need it in this way (You can use value tuple):
Dictionary<(string OfficeDebitId, System.DateTime? OfficeDebitDate, Enumerations.PaymentMethod? PaymentMethod), decimal> totalAmounts = products
.Where(p => p.ProductType == ProductType.ValueType)
.GroupBy(p => new { p.OfficeDebitId, p.OfficeDebitDate, p.PaymentMethod })
.ToDictionary(x => (x.Key.OfficeDebitId, x.Key.OfficeDebitDate, x.Key.PaymentMethod ), x => x.Sum(p => p.Amount));
I have two records for the same customer but with different customerLastUpdated dates, there is a way to return only the most recent one?
var response = await this.client.SearchAsync<ElasticCustomer>(searchDescriptor => searchDescriptor
.AllTypes()
.Query(q => q.Bool(b => b
.Should(
sh => sh.Match(m => m.Field(f => f.CustomerName).Query(query)),
sh => sh.Wildcard(w => w.Field(f => f.MobileNumber.Suffix("keyword")).Value($"*{query}*")))));
Query logic is Grouping the items by Id and Ordering it by Id. Then inside grouped items Ordering by Item1 then by Item2.
Linq query below,
var group1Items = MyList.GroupBy(g => g.Id)
.Where(w => w.Any(a => a.Code = 1)
.Select(s => new
{ key = s.Key,
items = s.OrderBy(o => o.Item1)
.ThenBy(t => t.Item2)
}
)
.OrderBy(o => o.Id)
.SelectMany(sm => sm.Items).ToList();
var group2Items = MyList.GroupBy(g => g.Id)
.Where(w => w.Any(a => a.Code = 2)
.Select(s => new
{ key = s.Key,
items = s.OrderBy(o => o.Item1)
.ThenBy(t => t.Item2)
}
)
.OrderBy(o => o.Id)
.SelectMany(sm => sm.Items).ToList();
MyList.Clear();
MyList.InsertRange(Mylist.Count, group1Items);
MyList.InsertRange(Mylist.Count, group2Items);
In the above two queries, only difference is Where condition. Is it possible to rewrite into single query?
Single query:
var groupItems = MyList.GroupBy(g => g.Id)
.Where(w => w.Any(a => a.Code == 1 || a.Code == 2)
.Select(s => new
{ key = s.Key,
items = s.OrderBy(o => o.Item1)
.ThenBy(t => t.Item2)
}
)
.OrderBy(o => o.Id)
.SelectMany(sm => sm.Items).ToList();
If Code 1 must come before Code 2:
var groupItems = MyList.GroupBy(g => g.Id)
.Where(w => w.Any(a => a.Code == 1)
.Select(s => new
{ key = s.Key,
items = s.OrderBy(o => o.Item1)
.ThenBy(t => t.Item2)
}
)
.OrderBy(o => o.Id)
.SelectMany(sm => sm.Items)
.Union(MyList.GroupBy(g => g.Id)
.Where(w => w.Any(a => a.Code == 2)
.Select(s => new
{ key = s.Key,
items = s.OrderBy(o => o.Item1)
.ThenBy(t => t.Item2)
}
)
.OrderBy(o => o.Id)
.SelectMany(sm => sm.Items)).ToList();
If you only want to avoid code duplication it may be easiest to capture a variable holding the code by which to filter.
int code = 0; // initialize with any value
var groupItems = MyList.GroupBy(g => g.Id)
.Where(w => w.Any(a => a.Code == code)
.Select(s => new
{
key = s.Key,
items = s.OrderBy(o => o.Item1)
.ThenBy(t => t.Item2)
})
.OrderBy(o => o.Id)
.SelectMany(sm => sm.Items); // No ToList() here!
MyList.Clear();
code = 1;
MyList.InsertRange(Mylist.Count, groupItems.ToList());
code = 2;
MyList.InsertRange(Mylist.Count, groupItems.ToList());
Removed where clause in the LINQ expression and implemented at InsertRange() method. This avoids redundant queries
var groupItems = MyList
.GroupBy(g => g.Id)
.Select(s => new
{ key = s.Key,
items = s.OrderBy(o => o.Item1)
.ThenBy(t => t.Item2)
}
)
.OrderBy(o => o.Id)
.SelectMany(sm => sm.Items).ToList();
MyList.Clear();
MyList.InsertRange(Mylist.Count, groupItems.Where(w => w.Code == 1));
MyList.InsertRange(Mylist.Count, groupItems.Where(w => w.Code == 2));
I am getting, with EF6, one advert by position as follows:
var adverts = context.Adverts
.Include(x => x.Files)
.Where(x => x.Position <= 32)
.OrderBy(x => Guid.NewGuid())
.GroupBy(x => x.Position)
.ToDictionary(x => x.Key, x => x.First());
I get one advert per group and each advert has one file.
But what I really want is a file for each advert so I tried:
var adverts = context.Adverts
.Include(x => x.Files)
.Where(x => x.Position <= 32)
.OrderBy(x => Guid.NewGuid())
.GroupBy(x => x.Position)
.ToDictionary(x => x.Key, x => x.First().Files);
In this case the value of the dictionary is empty.
Any idea how to solve this?
I have the following (working) code. It is very inelegant, and I think it can be refactored using Linq only and hence avoiding the foreach loop and having to rely on an external List<>. How to do this? Thanks
List<string> answerValues = new List<string>();
foreach (Fillings filling in fillings)
{
string answer = filling.Answers.Where(a => a.Questions == question)
.Select(a => a.Answer).FirstOrDefault();
if (!string.IsNullOrEmpty(answer)) answerValues.Add(answer);
}
IEnumerable<string> answerValues = fillings
.SelectMany(f => f.Answers)
.Where(a => a.Questions == question)
.Select(a => a.Answer)
.Where(ans => !string.IsNullOrEmpty(ans));
Or if you need a list:
IList<string> answerValues = fillings
.SelectMany(f => f.Answers)
.Where(a => a.Questions == question)
.Select(a => a.Answer)
.Where(ans => !string.IsNullOrEmpty(ans))
.ToList();
var answerValues = (
from f in fillings
from a in f.Answers
where a.Question == question
where !String.IsNullOrEmpty(a.Answer)
select a.Answer).ToList();
fillings.SelectMany(x => x.Answers.Where(a => a.Question == question)
.Select(a => a.Answer)
.FirstOrDefault())
.Where(x => !string.IsNullOrEmpty(x));