Null detection with Linq in Visual Studio 2022 - c#

I write the following code in VS2022:
var approvalResultHistory = cardData.CardData.SignTicketApproval
.OrderBy(x => x.CreateTime)
.Select(x => x.Result)
.Where(result => result != null)
.Select(result => new ApprovalResultHistory
{
ApproverName = _wackerUserService.GetUserProfileByEmail(result.ApproverEmail).DisplayName,
Outcome = result.Outcome,
Comment = result.Comment,
CreateTime = result.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
});
However, VS told me the "result" in the last Select maybe Null and give me a warning. I think I have already excluded all null values in Where. Do I miss something? or is VS making a false warning?
Thank you.

Related

Find usages of ITypeElement, or IDeclaredElement with Resharper SDK

I'm trying to create a custom navigate to plugin with the Resharper SDK plugin. I have managed to get the IDeclaredElement or ITypeElement when I stand on my type doing
var referenceName = dataContext.GetSelectedTreeNode<IReferenceName>();
var declaration = referenceName?.Reference.Resolve()?.DeclaredElement as ITypeElement;
if (declaration != null)
{
//TODO: Find all usages here and check if my type is used as single argument to a method (Visitor pattern)
}
The SDK docs are really sparse and I dont find anything on the subject. Thanks
After some trial and error i Found a working solution. IFinder.FindAllReferences
var foundMethods = declaration
.GetPsiServices()
.Finder
.FindAllReferences(declaration)
.Select(r => ((r.GetTreeNode().Parent as IUserTypeUsage)?
.Parent as IRegularParameterDeclaration)?
.Parent as IFormalParameterList)
.Where(list => list != null && list.ParameterDeclarations.Count == 1)
.Select(m => m.Parent as IMethodDeclaration)
.Where(m => m != null)
.ToList();
Full code here

Nullable Boolean value not working in Entity Framework

I have below lambda expression for select list of my model.
Note: state variable can be True, False or NULL.
var list = APPEntites.Submited_Files
.Where(r => r.Category == id.Trim() && r.approved == (bool?) state)
.OrderByDescending(r => r.Date_Created)
.ToList();
I have an issue with selecting. If I pass this STATE variable with Null, it will return 0 list items, but if I use null, it will return the rows correctly. I want to know the reason for this issue.
Note: this code was working perfectly before.
Thank you all.
Restarting Visual studio solved the issue.Strange!!.
var list = APPEntites.Submited_Files
.Where(r => r.Category == id.Trim() && r.approved == state)
.OrderByDescending(r => r.Date_Created)
.ToList();

Improve Linq query performance that use ToList()

this code written by #Rahul Singh in this post Convert TSQL to Linq to Entities :
var result = _dbContext.ExtensionsCategories.ToList().GroupBy(x => x.Category)
.Select(x =>
{
var files = _dbContext.FileLists.Count(f => x.Select(z => z.Extension).Contains(f.Extension));
return new
{
Category = x.Key,
TotalFileCount = files
};
});
but this code have problem when used inside database context and we should use ToList() like this to fix "Only primitive types or enumeration types are supported in this context" error :
var files = _dbContext.FileLists.Count(f => x.Select(z => z.Extension).ToList().Contains(f.Extension));
the problem of this is ToList() fetch all records and reduce performance, now i wrote my own code :
var categoriesByExtensionFileCount =
_dbContext.ExtensionsCategories.Select(
ec =>
new
{
Category = ec.Category,
TotalSize = _dbContext.FileLists.Count(w => w.Extension == ec.Extension)
});
var categoriesTOtalFileCount =
categoriesByExtensionFileCount.Select(
se =>
new
{
se.Category,
TotalCount =
categoriesByExtensionFileCount.Where(w => w.Category == se.Category).Sum(su => su.TotalSize)
}).GroupBy(x => x.Category).Select(y => y.FirstOrDefault());
the performance of this code is better but it have much line of code, any idea about improve performance of first code or reduce line of second code :D
Regards, Mojtaba
You should have a navigation property from ExtensionCategories to FileLists. If you are using DB First, and have your foreign key constraints set up in the database, it should do this automatically for you.
If you supply your table designs (or model classes), it would help a lot too.
Lastly, you can rewrite using .ToList().Contains(...) with .Any() which should solve your immediate issue. Something like:
_dbContext.FileLists.Count(f => x.Any(z => z.Extension==f.Extension)));

C# Lambda with Entity Framework - Return a result even when no match

The code below is working, but if it can't find an entry with "Domain Administrator" as per the where clause it will completely ignore anything else on that particular result. This leads to me missing items, as the view I am generating may not have a "Domain Administrator" entry. I understand that this is because it is an explicit where, but I'm not quite sure how to represent exactly what I need to do. I suspect I need to do a LEFT JOIN, but not sure how this then effects the navigation properties. Any guidance into the right direction would be appreciated.
var endpointConstructor = db.tbl_equipment.Include(t => t.tbl_Backup_Configuration)
.Where(e => e.tbl_Backup_Configuration.FirstOrDefault().BackupType == null)
.Where(e => e.tbl_customer.Calc_Contract_Status == true && e.Calc_Contract_Status == true && e.Equip_type.Contains("server")).OrderBy(e => e.tbl_customer.Priority)
.Where(what => what.tbl_customer.tbl_user_pass_list.FirstOrDefault().Usage1 == "Domain Administrator")
.Select(s => new CompanyServerUserPassViewModel { Comp_ID = s.Comp_ID, ServerName = s.NetBIOS_name, AdminUsername = s.tbl_customer.tbl_user_pass_list.FirstOrDefault().Username,
AdminPassword = s.tbl_customer.tbl_user_pass_list.FirstOrDefault().Password, Company = s.Company, TeamviewerID = s.tbl_computerinfo.FirstOrDefault().teamviewerID });
Something along the lines of:
.Where(what => [statement that evaluates to true if there is no domain admin]
|| what.tbl_customer.tbl_user_pass_list.First().Usage1 == "Domain Administrator")

Remove from a list where a elements value is null

I am trying to remove from a list in a list where there are null.
For Example:
responses.Questions[0].Options[0].Value = "asdf";
responses.Questions[0].Options[1].Value = null;
responses.Questions[0].Options[2].Value = 1;
I want to remove the second options in the list because the value is null. So When I am done I have a list like so:
responses.Questions[0].Options[0].Value = "asdf";
responses.Questions[0].Options[1].Value = 1;
I tried the code below but it doesn't appear to work:
responses.Questions.Select(q => q.Options.RemoveAll(o => o.Value == null));
use foreach:
foreach(var q in responses.Questions)
{
q.Options.RemoveAll(o => o.Value == null);
}
Try this
responses.Questions.ForEach(q => q.Options.RemoveAll(o => o.Value == null));
Use a Where clause in order to exclude null option lists:
responses.Questions
.Where(q => q.Options != null)
.ForEach(q => q.Options.RemoveAll(o => o.Value == null));
(According to one of your comments that is deleted now, you got an exception because of Options being null.)
Note: null values can appear at different levels here. responses, Questions, q and Options could theoretically all be null. Add tests where appropriate.

Categories

Resources