Get Values from single column based on condition - c#

I have query and I can display values based on condition in SQL. But how can write C# LINQ query is my question.
SELECT Value
FROM db.table
WHERE xxId = 1 AND YYid = 2 AND IsActive = '1' AND IsDeleted = '0'
Result
NNNN
MMMM
TTTT
VVVV
LLLL
I need same query in LINQ C#
var results = db.table
.Select(a => a.xxid == xxid && a.yyid == id &&
a.IsActive && !a.IsDeleted).value;

var results = db.table
.Where(a => a.xxid == xxid && a.yyid == id && a.IsActive && !a.IsDeleted)
.Select(a => a.value)
.ToList();

Related

How to write a linq query to exclude some of the records?

This is my LINQ
IList<string> ExceptList = new List<string>() { "045C388E96", "C9B735E166", "02860EB192", "2401016471" };
var listusers = context.USER_INFO.Where(x => x.ACTIVATED
&& x.COMP.EQUIPMENT.Count(y => y.STATUS == (int)STATUSEQ.ACTIVE) > 0
&& (x.LAST_LOGIN < time)
&& !ExceptList.Contains(x.COMP.CODE)
&& !x.IS_LOCK
|| !x.COMP.IS_LOCK)
.Select(x => new EmailOutOfDateLoginModel
{
COMPCode = x.COMP.CODE,
First_Name = x.FIRST_NAME,
Last_Name = x.LAST_NAME,
Total_EQ = x.COMP.EQUIPMENT.Count(y => y.STATUS == (int)STATUSEQ.ACTIVE),
User_Email = x.USER_EMAIL
}).ToList();
I am not sure why my ExceptList is not working. I want to exclude any record that contaisn any of the CODE in the ExceptList
Put parentheses around the expressions containing the && logic. The || at the end is only matched with the !x.IS_LOCK || !x.COMP.IS_LOCK otherwise.
According your linq all records where (!x.COMP.IS_LOCK==true) will be included in the query. Try this "where" part:
.Where(x => x.ACTIVATED
&& x.COMP.EQUIPMENT.Count(y => y.STATUS == (int)STATUSEQ.ACTIVE) > 0
&& (x.LAST_LOGIN < time)
&& !ExceptList.Contains(x.COMP.CODE)
&& !(x.IS_LOCK && x.COMP.IS_LOCK))

Only check date condition when DateTime?(nullable?) using LINQ

I need check if any record exists on current date. But AddOn is nullable date. If I check below condition is throwing error because I am trying get date from null.
var cusRelationships = SvcClient.Client.Context.CusRelationships.Where(c =>
c.CustomerId == identity.rCustomerId &&
c.AddedOn.Value.Date == DateTime.Now.Date).Select(c => c).ToList();
How compare date for current date?
Just check for null before the using the Value.
var cusRelationships = SvcClient.Client.Context.CusRelationships.Where(c =>
c.CustomerId == identity.rCustomerId &&
c.AddedOn.HasValue &&
c.AddedOn.Value.Date == DateTime.Now.Date).Select(c => c).ToList();
var cusRelationships = SvcClient.Client.Context.CusRelationships
.Where(c =>
c.CustomerId == identity.rCustomerId &&
c.AddedOn.HasValue &&
c.AddedOn.Value.ToShortDateString() == DateTime.Now.ToShortDateString())
.Select(c => c)
.ToList();

Linq - Dynamic Condition

I have the following query :-
I want to add one more condition which is dynamic, so if user passes DATEOFBIRTH it should be e.DateOfBirth <= date.
var data = ctx.Employee.Where(e => e.Id == Id
&& e.Category == Category
&& e.DateOfJoining <= date)
.Select(e => e)
.ToList();
How to condition dynamically?
You can use reflection to solve this problem but there is another idea that may helps you:
var criteria = new Dictionary<string, Func<Employee, bool>>();
var date = DateTime.Now; //or any other value
//Initialize your criterias
criteria.Add("DATEOFBIRTH", e => e.DateOfBirth <= date);
criteria.Add("DateOfJoining", e => e.DateOfJoining <= date);
var selectedValue = "DATEOFBIRTH";
var data = ctx.Employee.Where(e => e.Id == id &&
e.Category == Category &&
criteria[selectedValue](e)).ToList();
So if you change the selectedValue the output will be based on corresponding criteria you are looking for.
From your comment:
If the DateOfBirth is choosen, there where condition should be appended
by one more condition e.DateOfBirth <= date.. if user chooses
DateOfAnniversary then it should be e.DateOfAnniversary <= date
Then you could use:
var data = ctx.Employee
.Where(e => e.Id == Id && e.Category == Category && e.DateOfJoining <= date);
Now, assuming that filterbyDateOfBirth and filterbyDateOfAnniversary are bools:
if(filterbyDateOfBirth)
data = data.Where(e => e.DateOfBirth <= date);
if(filterbyDateOfAnniversary)
data = data.Where(e => e.DateOfAnniversary <= date);
var list = data.ToList();
Due to LINQ's deferred execution the database is queried just once at ToList.
Sounds like you're trying to do the following:
var employees = ctx.Employee.Where(e => e.Id == Id
&& e.Category == Category
&& e.DateOfJoining <= date);
if (!string.IsNullOrWhiteSpace(DATEOFBIRTH))
{
employees = employees.Where(e => e.DateOfBirth <= DATEOFBIRTH);
}
var data = employees.ToList();
You could also do the following, which is more concise, but since it looks like you are querying a database here, I would prefer the above approach since it doesn't include anything unnecessary in the query.
var data = ctx.Employee.Where(e => e.Id == Id &&
e.Category == Category &&
e.DateOfJoining <= date &&
(string.IsNullOrWhiteSpace(DATEOFBIRTH) ||
e.DateOfBirth <= DATEOFBIRTH))
.ToList();

How can I use Sum() in Linq?

How do I convert this statement into LINQ?
SELECT Sum(Balance) FROM account WHERE name='stocks' AND userid=290;
decimal sumLineTotal = (from od in account
where name == 'stocks' && userid == 290
select Balance).Sum();
var sum = db.account.Where(a => a.name == "stocks" && a.userid == 290)
.Sum(a => a.Balance);
Like this:
myBalanceSum = account.Where(x => x.name == 'stocks' && x.userid == 290 ).Sum(x => x.Balance);

Linq search that ignores nulls

How can I make a linq search that ignores nulls (or nullables)?
I have a method
IEnumerable<X> Search(int? a, int? b, int? c)
And I want it to return matches on any of the ints? that are not null.
IE: if a and c have values 1 and 9 and b is null the search should render (roughly) to
SELECT *
FROM [TABLE]
WHERE a = 1
AND c = 9
My real method will have 5+ paramters, so iterating combinations is right out.
IEnumerable<X> query = items;
if (a.HasValue) {
query = query.Where(x => x.a == a.Value)
}
if (b.HasValue) {
query = query.Where(x => x.b == b.Value)
}
if (c.HasValue) {
query = query.Where(x => x.c == c.Value)
}
var result = from row in table
where (!a.HasValue || row.a == a.Value)
&& (!b.HasValue || row.b == b.Value)
&& (!c.HasValue || row.c == c.Value)
select row;

Categories

Resources