Where is the DefaultIfEmpty with the linq query style - c#

var query = from r in list where r.Id == "" DefaultIfEmpty(String.Empty)
does not work.
How do I have to write a linq query with query style and use the DefaultIfEmpty method?

Assuming your list contains the type Item you would want:
// define your default item
var defaultItem = new Item { ... };
var query = (from r in list where r.Id == "" select r).DefaultIfEmpty(defaultItem);
or in method syntax
var query = list.Where( r => r.Id == "" ).DefaultIfEmpty(defaultItem);
However if you're selecting a specific string property of Item then you may want something like
var query = (from r in list where r.Id == "" select r.StringProperty)
.DefaultIfEmpty(string.Empty);

DefaultIfEmpty is used usually with JOINS, (outer joins).
You may see: How to: Perform Left Outer Joins (C# Programming Guide)
For your case it apears you want to select empty string if the r.Id is null, you can you can do:
var query = from r in list
select new
{
ID = r.Id == null ? string.Empty : r.Id
};

Related

Convert SQL query to LINQ or lambda expression in C# and use in EF Core

I have 3 table
Tbl_City , Tbl_GroupCities , Tbl_CtrCar .
I want to convert this SQL query to LINQ or lambda expression in C#
declare #fk_group uniqueidentifier
SELECT #fk_group= FK_Group
FROM dbo.Tbl_User
WHERE UserName='meysam'
SELECT dbo.Tbl_City.ID_City, dbo.Tbl_City.Name_City,COUNT( dbo.Tbl_CtrCar.Cur_year)
FROM dbo.Tbl_City
INNER JOIN dbo.Tbl_CtrCar ON dbo.Tbl_City.ID_City = dbo.Tbl_CtrCar.FK_City
WHERE ID_City IN (SELECT FK_City
FROM dbo.Tbl_GroupCities
WHERE Active=1 AND ID_Group=#fk_group)
GROUP BY ID_City , Name_City
I try it but it's not work
var model = _TblUser.FirstOrDefault(x => x.UserName == "sampleUserName");
var q = _TblGroupCities.Where(x => x.IdGroup == model.FkGroup && x.Active == true);
var sample2 =
(from x in _TblCity
join a in _TblGroupCities on x.IdCity equals a.FkCity
where a.Active == true && a.IdGroup == model.FkGroup
select new
{
x.IdCity,
x.NameCity
}).ToList();
Please take a look here the features you have in your query are not yet implemented. GroupBy and i think also subselects will do an
SELECT * FROM TableName
And in memory it will do the group by or even for each row a new SQL query.
Better to use the RawSql method for this purpose.
But if you realy want to learn LINQ and convert your SQL take a look at LINQPad
This issue is done. I found my problem, I don't Understand use two joins and use group by in Linq
I use this linq for the solution and run
var model = _TblUser.SingleOrDefault(x => x.UserName == type.UserName);
var q = _TblGroupCities.Where(x => x.IdGroup == model.FkGroup && x.Active == true);
tblCityViewModel = new List<MohasebKhodro.ViewModels.TblCityViewModel>();
var sample2 =
(from x in _TblCity
join a in _TblGroupCities on x.IdCity equals a.FkCity
where a.Active == true && a.IdGroup == model.FkGroup
select new
{
x.IdCity,
x.NameCity
}).ToList();
foreach (var item in sample2)
{
var er = _TblCtrCar.Where(x => x.FkCity == item.IdCity).Max(x => x.CurYear);
tblCityViewModel.Add(new MohasebKhodro.ViewModels.TblCityViewModel
{
IdCity = item.IdCity,
NameCity = item.NameCity,
MaxCurrentYear = Convert.ToString(er)
});
}

loading sequence from except

I have these two tables.
var cardtagtable = (from u in db.CardTagTables
where u.FKCardTagID == cardtable.cardID
select u.CardTagName).ToList();
var tagtable = (from u in db.TagTables
select u.TagName).ToList();
Where in cardtagtable all names are selected to match with tagtable's name.
Condition-
I want names from tagtable except names coming from cardtagtable list.
so I tried here-
var list = tagtable.Except(cardtagtable);
This list is a sequence of all names except from cardtagtable.
Everything is all right till now.
Now I will use this list and pass it through the model.
var taglist = (from u in list
select new TagModel {
tagId = u.TagID,
tagName = u.TagName,
tagCount = Convert.ToInt32(u.TagCount) == null ? 0 : Convert.ToInt32(u.TagCount),
}).ToList();
But this query says me no definition found for Model values from u.
How do I use this list here in this case?
Because u is probably a string because your list is a IEnumerable<string>.The reason is that you are only selecting your TagNames, so your list contains only tag names, not your TagTables.Instead you need to select your elements instead of just tag names:
var cardtagtable = (from u in db.CardTagTables
where u.FKCardTagID == cardtable.cardID
select u).ToList();
var tagtable = (from u in db.TagTables
select u).ToList();
Then use Where and Any instead of Except like this:
var list = tagtable.Where(c => !cardtagtable
.Any(x => x.CardTagName == c.TagName));
Then your last query should work fine.
Update: Also there is a more elegant and optimized way to do that (especially if this is LINQ to SQL).You can select only CardtagNames from cardtagtable and use Contains method:
var cardtagtable = (from u in db.CardTagTables
where u.FKCardTagID == cardtable.cardID
select u.CardTagName).ToList();
var tagtable = (from u in db.TagTables
select u).ToList();
var list = tagtable.Where(c => !cardtagtable.Contains(c.TagName));

using linq to sql to specify where clause

I am using this method to get results to fill my grid but this method is also used to fill another grid which requires a where clause with two params and this one
only needs one. Even though i passed in null of the param that isn't used but still it is returning no results because of the where clause. Any advice of how i could
change this maybe use linq to sql where i call the method to specify the where clause instead of in the method getting data?
DocsForReview.DataSource = docLib.GetGrid(Guid.Empty, lib);
using (var dc = new DocMgmtDataContext())
{
var subs = (from doc in dc.Documents
join u in dc.Users on doc.OwnedByUserID equals u.ID
where doc.OwnedByUserID == usr && doc.LibraryID == lib
select new StudentDocuments
{
DocID = doc.ID,
Assignment = doc.Library.Name,
Submitted = doc.UploadDT,
Student = u.FullName
}).OrderByDescending(c => c.Submitted).AsEnumerable().ToList();
return subs;
}
For nullable types try this:
doc.LibraryID == (lib ?? doc.LibraryID)
In your case (a System.Guid) you can try this:
doc.LibraryID == (lib == Guid.Empty ? doc.LibraryID : lib)

Linq To Entities

I have a small problem in my where clause in the linq expression below. If I put the number 3 instead of department.Id I get the desired result but when I use department.Id I get nothing in the resultset.
I also want to get a count for the number of filters for that filter name using the query again using distinct.
var dept = Page.RouteData.Values["department"];
var department = (from d in db.Departments
where d.Name.Replace(" ", "-") == dept
select new {d.Id, d.Name}).FirstOrDefault();
var query = from p in db.Products
join f in db.ProductFilters on p.Id equals f.ProductId into filters
from x in filters.Where(x => x.Product.DepartmentId == department.Id
/* if == 3 it works */)
select new { x.Name, x.Id };
Promoted to answer from comments:
Have you checked that the department instance is as you think it should be after the first linq statement - ie has an Id == 3?
Your first query is not finding any valid department and is therefore returning default which most probably means that departmend.Id == 0.

Linq - Retrieve a single value in a String

I use Asp.net 3.5 and EF 4.
I need find a specific row in my DataBase and display on a label a single value as string.
At the moment I use this code, it is working, so I find a single Object and read its properties.
var myAuthor = (from at in context.CmsAuthors
where at.AuthorId == myRow.AuthorId
select at).Single();
myAuthorNameLabel.Text = myAuthor.LastName;
I would like to know:
If there is another syntax in Linq to achieve the same result.
How to do it using Lamba?
Which approach would you suggest me?
Here's the method syntax (using lambdas)
myAuthorNameLabel.Text = context.CmsAuthors
.Where(at => at.AuthorId == myRow.AuthorId)
.Select(at => at.LastName)
.SingleOrDefault() ?? string.Empty;
You can use:
var myAuthorName =
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Single().Select(a => a.LastName);
actually this would be even better:
var myAuthorName =
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Select(a => a.LastName).Single();
Update
An example of how to use with Anonymous type:
var myAuthorNames =
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Select( a => new {a.LastName, a.FirstName}).Single();

Categories