How to give conditional where clause in a single linq query? [duplicate] - c#

This question already has answers here:
Linq: adding conditions to the where clause conditionally
(9 answers)
Closed 6 years ago.
I have a query, which will give the result set . based on a condition I want to write the where clause. that means . I have a variable x, if the value of x is "ALL" then I don't want to add this condition at all.if the value is not "ALL" then I need to add a where clause (where st.address==x). how can I add this condition in below query .
var abc=(from st in Context.STopics join ap in Context.ATopic on st.id equals ap.id
where st.address==x
select new result()
{
name = st.name
add= ap.add}).ToList();

Here is what you're looking for:
var yourQuery = Context.STopics.AsQueryable();
var yourParam = "ALL";
if(yourParam != "ALL")
yourQuery = yourQuery.Where(x => x.IsActive==true && x.StudentID == 123);
var abc = yourQuery.Select(x=> new result()
{
name = st.name
}).ToList();
The thing is that with linQ you don't get your data from query right away. So you can construct your actual query this way as you need.

You can make your condition in a way that matches all elements when x = "ALL" and otherwise match your other conditions:
var abc=(from st in Context.STopics
where x == "ALL" || (st.IsActive==true && st.StudentID == 123)
select new result()
{
name = st.name }).ToList();

Something like:
var abc=(from st in Context.STopics
where (x!="All" ? (st.IsActive==true && st.StudentID == 123) )
select new result()
{
name = st.name
}).ToList();

Related

How to write a recursive Linq query in my case?

I have a recursive Group table - a hierarchical structure in which each of the groups refers to the upper one.
I want to build a query in which I provide the initial value of the group and I want to find all the groups that refer to it.
I wrote something like this, but how to make a universal version (the topmost group is one and it has no reference to the next one (GroupId == null)):
var res = from g in _context.Groups
where g.Status == 3
where g.GroupId == initGroupId || g.GroupNavigation.GroupId == initGroupId ||
g.GroupNavigation.GroupNavigation.GroupId == initGroupId
select new GroupExtendedModel
{
Id = g.Id,
TypeName = g.TypeNavigation.Type,
Name = g.Name,
GroupId = g.GroupId,
CompanyId = g.Company,
TypeId = g.Type,
GroupAccessType = GroupAccessType.Down
};

How to write LINQ query row numbers in C#? [duplicate]

This question already has answers here:
How do you add an index field to Linq results
(3 answers)
Closed 3 years ago.
SQL:
Select top percent a,b,ROW_NUMBER() over(PARTITION BY a,b order by a,b) as rowsnumber
from Students as s
group by a,b
LINQ:
var students=from p in Students
group p by new{p.a,p.b} into grp
order by grp.Key.a,grp.Key.b
.Select(s=>s.a,s.b).ToList();
I want to this SQL query convert to LINQ but not convert.
var list = FileList.Select((file, index) => new { Index=index, Filename=file });
Maybe so for example.
Like the other answer indicates, the Select method has a handy overload with the index parameter. It requires the method LINQ syntax though (and not the query syntax) So, the following query should do the trick. Note that it combines both: query and method syntax as I tried to keep it close to the code in the question above.
var studentGroups=
from p in Students
group p by new { p.a, p.b };
var students =
from gr in studentGroups
from st in Students
.Where(s => s.a == gr.Key.a && s.b == gr.Key.b)
.Select((s,i) => new { s.a, s.b, s.c, s.d, rn = i + 1 })
orderby st.a, st.b
select st;
I convert your sql query to lambda.
var students = context.GroupBy(g => new { g.A, g.B }).Select((s, index) => new {
s.Key.A,
s.Key.B,
rowsnumber = index + 1
}).Take(10).ToList();
Group by is working like partition by.
Index start from 0, so converting to row number to need add 1.
Take is select TOP 10 rows.

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

LINQ - using result from one in another

I'm completely new to LINQ, i want to rewrite some of mine SQL querys into LINQ (just to learn) and i'v already stuck at the beginning. Probably solution is very simple but as i'v said I'm completely new and i didn't find solution to this.
I have one query :
string typMoneta = textBox1.Text;
var moneta = from x in db.grupyTowarowes
where x.typ == typMoneta
select new
{
x.grupa
};
Which works ok and when i set
dataGridView1.DataSource = moneta;
Then i got output
And i want to use this output in my second query :
var query = from c in dbContext.Picking
where c.Number == 1000 && c.Group == moneta
select new
{
c.id
};
Problem is with c.Group == moneta. I don't know the correct syntax. Could someone help me?
I think you meant to use moneta.Contains(c.Group). In first query, make sure you use ToList() to load data into memory.
IList<string> moneta = (from x in db.grupyTowarowes
where x.typ == typMoneta
select x.grupa).ToList();
var query = (from c in dbContext.Picking
where c.Number == 1000 && moneta.Contains(c.Group)
select c.id).ToList();
The moneta is an IEnumerable<T> where T in your case is the type of grupa
That being said you should write your query like below:
var query = from c in dbContext.Picking
where c.Number == 1000
&& moneta.Contais(c.Group)
select new
{
c.id
};
or in fluent syntax like below:
var query = dbContext.Picking
.Where(pick => pick.Number == 1000
&& moneta.Contains(pick.Group))
.Select(pick => pick.id);
Note that moneta is not a collection of strings. It's a collection of objects that have a string property named "grupa".
Does this work for you?
var query =
from c in dbContext.Picking
where c.Number == 1000
&& moneta.Any(m => m.grupa == c.Group)
select new { c.id };
You could also do this:
// Get list of strings
var groups = moneta.Select(m => m.grupa).ToList();
// Get items where "Group" value is one of the strings in groups list, above.
var query =
from c in dbContext.Picking
where c.Number == 1000
&& groups.Contains(c.Group)
select new { c.id };

Proper use of StartWith and Contains in Entity Framework

I want to remove prefixes from StoreName field in Linq Linq to Entity query.
I have following query which gets list of all prefixes in table
Query1
var _prefix = context.Prefixes.Select(pre => pre.Prefix1);
I want to use this result in Query2
Query2
var objRetailer = from stores in context.RetailerStoredtls
join ret in context.RetailerContactdtls
on stores.RetailerID equals ret.RetailerID
join retreg in context.RetailerRegDates
on stores.RetailerID equals retreg.RetailerRegDateId
where (stores.IsDeleted == null || stores.IsDeleted == false)
&& (stores.CreatedDate.Value.Year == iYear || stores.ModifiedDate.Value.Year == iYear)
&& retreg.IsApproved== true
orderby stores.StoreName
select new
{
stores.StoreID,
Store = stores.StoreName,
Area = stores.StoreCity,
Zip = stores.StoreZip,
SellingCard = (storessellingcard.Contains(stores.RetailerID.Value) ? true : false)
StoreWithoutPrefix = stores.StoreName.StartsWith(<one of prefix retrieved from Query1> ? stores.StoreName : <stores.StoreName without prefix>
};
Unfortunately we have .StartWith() that take only string parameter not result of Query1, if I go with .Contains it will not check for whether it starts with or not, it just check whether string is present there. What should I do to accomplish this task?
Thanks.
You can use IndexOf, but probably you have problems with case sensitivity. So add a parameter CompareOptions.IgnoreCase

Categories