Replacing empty values with a default value in a Linq to Entities query - linq

In the Linq to Entities query below I need to place a default value in the x.Number in the returned value if the query returns 0 OfficeTelephone objects. I have tried
x.Number??"555-1212" but that throws an error.
from c in Contacts
.Where(a => a.LastName.Contains("ANDUS")).Take(10)
select new
{
Id = c.Id,
OfficeTelephone = c.Telephones.Where(a=>a.TelephoneType.Name.Contains("Office")).Select(x => new { x.AreaCode, x.Number, x.TelephoneType, x.Primary })
}
I've tried something like:
from c in Contacts
.Where(a => a.LastName.Contains("ANDUS")).Take(10)
select new
{
Id = c.Id,
OfficeTelephone = c.Telephones
.Where(a=>a.TelephoneType.Name.Contains("Office"))
.Select(x => new { x.AreaCode, x.Number, x.TelephoneType, x.Primary })
.DefaultIfEmpty()}
But I'm not sure how to push a default object into the DefaultIFEmpty()

Use DefaultIfEmpty and pass a default instance with those value which you would want by default i.e. if no rows are returned.
try it like this:
Contacts.Where(a=>a.LastName.Contains("ANDUS"))
.Take(10)
.Select(x => new
{
Id = x.Id,
OfficeTelephone = x.Telephones
.Where(a=> a.Telephone.Name.Contains("Office"))
.Select(b=> new Telephone
{
b.AreaCode,
b.Number,
b.TelephoneType,
b.Primary
})
.DefaultIfEmpty(new Telephone())
});
where I've assumed that typeof(x.Telephones) == typeof(List<Telephone>)

Related

How can I add Sum from another Table in my Model?

So I have my View setup like this in the controller:
public ActionResult View(Guid projectID)
{
OnboardModel model = context.onboard_projectInfos.Where(x => x.projectID == projectID).Select(x =>
new OnboardModel()
{
propertymanagername = x.propertymanagername,
propertymanagercontactemail = x.propertymanagercontactemail,
date_modified = (DateTime)x.date_modified,
projectmanagercontactnumber = x.projectmanagercontactnumber,
Developer = x.onboard_projectCreate.Developer,
status1 = x.onboard_projectCreate.status1,
ProjectName = x.onboard_projectCreate.ProjectName
}).SingleOrDefault();
var pix = projectID.ToString();
context.onboard_BuildingInfos.Where(x => x.buildprojectID == pix).GroupBy(x => x.buildprojectID).Select(g => {
model.totalres = g.Sum(b => b.numberofres);
model.totalcom = g.Sum(b => b.numberofcommer);
});
return View(model);
}
Problem is grabbing the sum of numberofres and numberofcommer from BuildingInfos.
Using .Select gives me the error:
Error CS0411 The type arguments for method 'Queryable.Select(IQueryable, Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
How to I write this LINQ statement correctly?
Thanks.
You cannot modify an object within a select (you can only create a new object). Further, you can't add new properties to an existing object.
We'll assume that OnboardModel defines the totalres and totalcom properties.
var query = context.onboard_BuildingInfos
.Where(x => x.buildprojectID == pix)
.GroupBy(x => x.buildprojectID);
foreach(var g in query)
{
model.totalres = g.Sum(b => b.numberofres);
model.totalcom = g.Sum(b => b.numberofcommer);
}

LINQ group by ID - Distinct by order

I have data in a generic list named "Assignment" as shown in the Original table. Want to group by ID and display only one record based on US-UK-India order.
The result should transform from first table to second as shown in the attached image.
Try this:
SQL like syntax.
from a in Assignments
group a by a.Id into gr select gr.FirstOrDefault()
Lambda expression:
Assignments
.GroupBy (a => a.Id)
.Select (gr => gr.FirstOrDefault ())
Try this, its works. I hope this is what you need.
var query01 = context.FirstTable
.GroupBy(p => p.ID
,(ky, el) => new { ky.Value , FirstCountry = el.Select(p => Country).Take(1)});
var Result = query01
.Join(context.FirstTable
, ul => new
{
Id = ul.Value
,Country = ul.FirstCountry.FirstOrDefault()
}
, fl => new
{
Id = (int)fl.ID
, Country = fl.Country
}
, (ul, fl) => new { fl }).ToList();

Linq select subquery

As the title states, I'm trying to perform a select subquery in Linq-To-SQL. Here's my situation:
I have a database view which returns the following fields:
SourceId
LicenseId
LicenseName
CharacteristicId
CharacteristicName
Now I want to be able to store this in a model of mine which has the following properties
Id
Name
Characteristics (this is List which has Id, Name and Icon => Icon is byte[])
Here's the query I wrote which doesn't work:
var licensesWithCharacteristics =
_vwAllLicensesWithAttributesAndSourceIdRepository.GetAll()
.Where(x => x.SourceID == sourceId)
.Select(a => new LicenseWithCharacteristicsModel()
{
LicenseId = a.LicenseId,
LicenseName = a.LicenseName
,CharacteristicList = _vwAllLicensesWithAttributesAndSourceIdRepository.GetAll()
.Where(x => x.LicenseId == a.LicenseId)
.Select(c => new CharacteristicModel { Id = c.CharacteristicID, Name = c.CharacteristicName, Icon = c.Icon })
.Distinct().ToList()
})
.Distinct().ToList();
How would you solve this? I'm trying to do this in one query to keep my performance up, but I'm kind of stuck.
Your sample query and models are not that coherent (where does Icon come from, Characteristics or CharacteristicList), but anyway.
I do this in two parts, you can of course regroup this in one query.
I enumerate the result after the grouping, you may try to do without enumerating (all in linq to sql, but not sure it will work).
var groupedResult =
_vwAllLicensesWithAttributesAndSourceIdRepository.GetAll()
.Where(x => x.SourceID == sourceId)
.GroupBy(m => new {m.LicenseId, m.LicenseName})
.ToList();
var results = groupedResult.Select(group => new LicenseWithCharacteristicsModel {
LicenseId = group.Key.LicenseId,
LicenseName = group.Key.LicenseName,
Characteristics = group.Select(m=> new CharacteristicModel {
Id = m.CharacteristicId,
Name = m.CharacteristicName
}).ToList()
});
in "single query"
_vwAllLicensesWithAttributesAndSourceIdRepository.GetAll()
.Where(x => x.SourceID == sourceId)
.GroupBy(m => new {m.LicenseId, m.LicenseName})
.Select(group =>
new LicenseWithCharacteristicsModel
{
LicenseId = group.Key.LicenseId,
LicenseName = group.Key.LicenseName,
Characteristics = group.Select(m =>
new CharacteristicModel
{
Id = m.CharacteristicId,
Name = m.CharacteristicName
}).ToList()
});

Orderby and Linq

How can i add orderby to this:
return (from m in response["holder"].Children()
orderby m["name"]
select new SelectListItem
{
Text = m["name"].ToString(),
Value = m["name"].ToString()
}).ToList();
The problem is that the json returned in the response variable has a list of names, all of them have an uppercase first letter apart from one so they all get ordered fine except the one with the lower case which gets stuck at the bottom of the SelectListItem list.
Any ideas?
Thanks in advance..
EDIT:
Additional info - i am using JSON.NET to parse the json response. And the response variable is a JObject.
You'll need to normalize the data during your orderby. In my example I've chosen to use the ToUpperInvariant() method:
return (from m in response["holder"].Children()
orderby m["name"].ToUpperInvariant()
select new SelectListItem
{
Text = m["name"].ToString(),
Value = m["name"].ToString()
}).ToList();
I'm also assuming that m["name"] is already a String object. If it's not, change the line to:
orderby m["name"].ToString().ToUpperInvariant()
Maybe something like this:
return (from m in response["holder"].Children()
orderby m["name"].ToString().ToLower()
select new SelectListItem
{
Text = m["name"].ToString(),
Value = m["name"].ToString()
}).ToList();
When using the OrderBy method in the method syntax, you can specifiy a StringComparer. Passing a StringComparer that ignores casing solves your issue:
response["holder"]
.Children()
.OrderBy(m => m["name"], StringComparer.CurrentCultureIgnoreCase);
response["holder"]
.Children()
.OrderBy(m => m["name"] as String, StringComparer.CurrentCultureIgnoreCase)
.Select(m => new SelectedListItem
{
Text = m["name"].ToString(),
Value = m["name"].ToString())
})
.ToList();
return response["holder"].Children()
.Select(m => m.FirstCharToUpper())
.OrderBy(m => m["name"].ToString())
.Select(m => new SelectedListItem{
Text = m["name"].ToString(),
Value = m["name"].ToString()
})
.ToList();
static class Utility
{
public static string FirstCharToUpper(this string s)
{
return s.First().ToString().ToUpper() + string.Join("", s.Skip(1));
}
}

Selecting related pairs LINQ

I'm using LINQ to manipulate a datatable. I have 3 columns - I would like group by one and then select the remaining 2 columns together. At the moment I have something like this
var query = reportDataTable.AsEnumerable()
.GroupBy(c => c["Code"])
.Select(g =>
new {
Code = g.Key,
Rank = g.Select(f => new
{ f["rank"],
f["Name"]}).ToArray()
});
but I get issues due to anonymous types. I know this syntax would work if I could reference the the column headers directly (in say a list or w/e). How can I get around this with DataTables? Cheers.
Edit:
Well I'd like to be able to reference the fields later when I come to populate the data into a different datatable:
foreach (var q in query)
{
DataRow df = dp.NewRow();
df["Code"] = q.Code;
foreach (var rank in q.Rank)
{
df[rank.name] = rank.rank;
}
dp.Rows.Add(df);
}
define your Rank fields, Also if you have a class for it, call related class constructor,
you can see this in bellow code, before ToArray.
var query = reportDataTable.AsEnumerable()
.GroupBy(c => c["Code"])
.Select(g =>
new { Code = g.Key, Rank =
g.Select(f => new { rank = f["rank"], name = f["Name"]})
.ToArray() });

Resources