Linq Query syntax System.Xml.Linq.XElement - linq

I am querying an Xelement and attempting to get string values into another object
Here is the Xml
<Test ID="2278388" TestCompleted="2013-06-25T14:13:07.137">
<TestResult>P</TestResult>
<TestType>
<Name>Nursing</Name>
<Part1>ULE</Part1>
<Part2>PRI</Part2>
</TestType>
<ExamCode>P1</ExamCode>
</Test>
using webclient i have manged to get this into an Xelement 'Elm'
I have worked out how to get the Name part1 and part2
but cant figure out how to get ID ,Testresult, Completed, or Exam Code
private BssClient XMLtoBssClient()
{
BssClient BssC = new BssClient();
BssC.caseType = ((wch.Elm).Descendants("TestType").Select(x => x.Element("Name").Value).FirstOrDefault()) ?? "";
BssC.matter1 = ((wch.Elm).Descendants("TestType").Select(x => x.Element("Part1").Value).FirstOrDefault()) ?? "";
BssC.matter2 = ((wch.Elm).Descendants("TestType").Select(x => x.Element("Part2").Value).FirstOrDefault()) ?? "";
BssC.ExamCode =
BssC.ID =
BssC.DateCompleted =
return BssC;
}
i have googled and looked on MSDN and tried various things
but this really new to me
Any help much appreciated

The following code should work:
private BssClient XMLtoBssClient()
{
BssClient BssC = new BssClient();
BssC.caseType = ((wch.Elm).Descendants("TestType").Select(x => x.Element("Name").Value).FirstOrDefault()) ?? "";
BssC.matter1 = ((wch.Elm).Descendants("TestType").Select(x => x.Element("Part1").Value).FirstOrDefault()) ?? "";
BssC.matter2 = ((wch.Elm).Descendants("TestType").Select(x => x.Element("Part2").Value).FirstOrDefault()) ?? "";
BssC.ExamCode = ((wch.Elm).Elements("ExamCode").Select(x => x.Value).FirstOrDefault()) ?? "";
BssC.TestResult = ((wch.Elm).Elements("TestResult").Select(x => x.Value).FirstOrDefault()) ?? "";
BssC.ID = ((wch.Elm).Attributes("ID").Select(x => x.Value).FirstOrDefault()) ?? "";
BssC.DateCompleted = ((wch.Elm).Attributes("TestCompleted").Select(x => x.Value).FirstOrDefault()) ?? "";
return BssC;
}
However I reccommend you look into Xml serialization as it will make this an awful lot easier to maintain and a lot simpler.

Related

How to count distinct

I'm implementing ASP.NET Core project and have a query like the following for finding count of distinct userId per operatorName, however it shows me error for the line count distinct after running the project:
var activeUserPerOperatorCount = requests.GroupBy(x => new { operatorName = x.Operator.Name, x.UserId }).Select(x => new
{
userIds = x.Key.UserId,
operatorNames = x.Key.operatorName,
activeUserPerOperatorCount = x.Select(l => l.UserId).Distinct().Count()
}).ToList();
I appreciate if anyone helps me how can I find distinct count of userId per operatorName in my query.
ok, the correct query is like the following and it works correctly:
var activeUserPerOperatorCount = requests.GroupBy(x => new { operatorName = x.Operator.Name}).Select(x => new
{
operatorNames = x.Key.operatorName,
activeUserPerOperatorCount = requests.Select(l => l.UserId).Distinct().Count()
}).ToList();

ef6 linq method returning $ref for nested entries in query

my linq method system from EF6 is returning $ref when I monitor results in fiddler. If I watch the local window in my webapi everything is populated correctly, but not in the actual results that are returned. It only affects the nested entries. anyone know what I am doing wrong? (I created models from database in EF6)
var student = dbEF.Accounts
.Where(x => x.AccountNumber == acctNum)
.Select(x => new DTOCrmDetails()
{
AccountNumber = x.AccountNumber,
CommissionId = x.CommissionId,
Commission = x.Commission,
ManagerID = x.ManagerID,
ManagerName = x.Manager.ManagerName,
Manager = x.Manager,
Employees = x.Manager.Employees,
WireInstructionsUSD = x.Manager.WireInstructionsUSDs
//Mapping_ManagersExecutingBrokers = x.Manager.Mapping_ManagersExecutingBrokers
}).FirstOrDefault();
return student;
these are my settings.
var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; config.Formatters.Remove(config.Formatters.XmlFormatter); config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
You need to disable your lazy loading in the entity framework dbcontext.
something like this way:
dbEF.Configuration.LazyLoadingEnabled = false;

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);
}

Using linq with PropertyValueCollection

I'd like to know if there is a way or more efficient way using Linq. Instead of using the while loop, is it possible to do a select where using Linq query?
public UserPrincipal GetUser(string sUserName, string spwd, string domain, string ou)
{
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, domain, ou, sUserName, spwd);
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
DirectoryEntry user = (DirectoryEntry)oUserPrincipal.GetUnderlyingObject();
PropertyCollection pc = user.Properties;
IDictionaryEnumerator ide = pc.GetEnumerator();
ide.Reset();
while (ide.MoveNext())
{
PropertyValueCollection pvc = ide.Entry.Value as PropertyValueCollection;
if (ide.Entry.Key.ToString() == "XYZ")
{
//Response.Write(string.Format("name: {0}", ide.Entry.Key.ToString()));
//Response.Write(string.Format("Value: {0}", pvc.Value));
}
}
.......;
.......;
}
Thanks!
The reason you can't use Where() on a PropertyCollection is because it implements the non-generic IEnumerable, when Where() is a method of only the generic version. You can convert a PropertyCollection to a generic IEnumerable by using Cast<T>().
var matches = pc.Cast<DictionaryEntry>().Where(p => p.Key.ToString() == "XYZ");
foreach( var match in matches )
{
Response.Write(string.Format("name: {0}", match.Key));
Response.Write(string.Format("Value: {0}", match.Value));
}
This way is doubtfully any more efficient.
Try this:
foreach (PropertyValueCollection pvc in pc.OfType<PropertyValueCollection>().Where(v => v.PropertyName == "XYZ"))
{
Response.Write(string.Format("name: {0}", pvc.PropertyName));
Response.Write(string.Format("Value: {0}", pvc.Value));
}
Besides, you can try to use ForEach:
pc.OfType<PropertyValueCollection>()
.Where(v => v.PropertyName == "XYZ")
.ToList()
.ForEach(pvc =>
{
Response.Write(string.Format("name: {0}", pvc.PropertyName));
Response.Write(string.Format("Value: {0}", pvc.Value));
});
This is a pretty old thread, but I was searching for a way to work with PropertyCollection using LINQ. I tried the suggested methods, but I always get an invalid cast exception when casting to DictionaryEntry. And with a DictionaryEntry, things like FirstOrDefault are funky. So, I simply do this:
var directoryEntry = adUser.GetUnderlyingObject() as DirectoryEntry;
directoryEntry.RefreshCache();
var propNames = directoryEntry.Properties.PropertyNames.Cast<string>();
var props = propNames
.Select(x => new { Key = x, Value = directoryEntry.Properties[x].Value.ToString() })
.ToList();
With that in place, I can then easily query for any property directly by Key. Using the coalesce and safe navigation operators allows for defaulting to an empty string or whatever..
var myProp = props.FirstOrDefault(x => x.Key == "someKey"))?.Value ?? string.Empty;
Note that the "adUser" object is the UserPrincipal object.

Weird behaviour with Linq

I have a Windows forms application (.NET 4.0) running with a Sql Server CE 3.5 database, which I access via an EF connection.
Here is my initial query, which returns two results:
var list = db.UserPresentation
.Select(up => new
{
UserPresentationID = up.UserPresentationID,
PresentationName = up.PresentationName,
DateRequested = up.DateRequested,
Edit = string.Empty,
Delete = string.Empty,
Download = string.Empty
})
.OrderByDescending(up => up.DateRequested)
.ToList();
Now I introduce an external variable and a where clause, and it returns zero results. If I run this same code in LinqPad, it returns 2 results.
int userID = 2;
// load list of user presentations
var list = db.UserPresentation
.Where(up => up.UserID == userID)
.Select(up => new
{
UserPresentationID = up.UserPresentationID,
PresentationName = up.PresentationName,
DateRequested = up.DateRequested,
Edit = string.Empty,
Delete = string.Empty,
Download = string.Empty
})
.OrderByDescending(up => up.DateRequested)
.ToList();
Now I hardcode the userid inside the query, and it returns two results again:
var list = db.UserPresentation
.Where(up => up.UserID == 2)
.Select(up => new
{
UserPresentationID = up.UserPresentationID,
PresentationName = up.PresentationName,
DateRequested = up.DateRequested,
Edit = string.Empty,
Delete = string.Empty,
Download = string.Empty
})
.OrderByDescending(up => up.DateRequested)
.ToList();
I'm really stumped. Any idea what's going on here?
Is UserID nullable?
If so be sure to do .Where(up => up.UserID.HasValue && up.UserID.Value == userID)
I had something similar with a nullable datetime once
Have you tried assigning the same hard coded value inside your variable? My guess is that the value in your variable is not found among your data, that is if you are sure that the variable name is correct.

Resources