filtering age of members using linq - c#

I am trying to check for people in a certain range - let minage and maxage corresponding for e.g. age group with minage=18 and maxage =24 meaning I am trying to filter out the people aged between 18 and 24.Also datatype for dob of member is string ..
i am trying this
int agefrom = Convert.ToInt32(cbGEFrom.Text);
int ageto = Convert.ToInt32(cbGETo.Text);
DateTime today = DateTime.Today;
DateTime max = today.AddYears(-(agefrom + 1));
DateTime min = today.AddYears(-(ageto));
string maxage = Convert.ToString(max);
string minage = Convert.ToString(min);
var members =
from report in eclipse.members
where string.Compare(report.member_Dob,minage) >=0
where string.Compare(report.member_Dob,maxage) < 0
select report;
i dont know is this way is correct or not ..
would any pls suggest any idea ..
many thanks in advance...

int agefrom = Convert.ToInt32(cbGEFrom.Text);
int ageto = Convert.ToInt32(cbGETo.Text);
DateTime today = DateTime.Today;
DateTime maxDOB = today.AddYears(-ageTo);
DateTime minDOB = today.AddYears(-ageFrom);
var members = eclipse.members.Where(m=>m.member_Dob>=minDOB && m.member_Dob<=maxDOB);
EDIT: Query comprehension is as under
var members = from member in eclipse.members
where member.member_Dob>=minDOB && member.member_Dob<=maxDOB
select member;

Comparing dates via their string value feels horridly wrong to me.
You say the type of the member_Dob field is string; I'd say there is something wrong with your model, it should be DateTime
If you can't change the underlying model, at least convert it in code (using DateTime.Parse). Then you can simply compare DateTimes in your where clause as per the other answers:
var members = from report in eclipse.members
let dob = DateTime.Parse(report.member_Dob) // or use ParseExact
where dob >= minDOB && dob < maxDOB
select report;

Related

The property 'ID' is part of the object's key information and cannot be modified in asp.net mvc

I have used entity framework with code first approach.
when I am trying to pass record one by one Fromdate to Todate, 1st time its work, after it gives error like: "The property 'ID' is part of the object's key information and cannot be modified."
var fd = todaycooked.CookDate; // 2016-07-01
var td = todaycooked.ToCookDate; //2016-11-01
for (var date = fd; date <= td; date = date.AddDays(1))
{
var product = db.Products.Find(todaycooked.ProductID);
product.Qty = product.Qty + todaycooked.QTY;
todaycooked.Product = product;
todaycooked.CookDate = date;
db.TodayCookeds.Add(todaycooked);
db.SaveChanges();
}
Thanks in Advance.
You are setting the Product and CookDate once per day, so I assume you want one record per day - which means you mean one object per day. I suspect you actually want something like:
var fd = todaycooked.CookDate; // 2016-07-01
var td = todaycooked.ToCookDate; //2016-11-01
// this doesn't change per day, so only fetch it once
var product = db.Products.Find(todaycooked.ProductID);
for (var date = fd; date <= td; date = date.AddDays(1))
{
var toAdd = todaycooked.Clone(); // TODO: add a suitable clone method
toAdd.Product = product;
toAdd.CookDate = date;
db.TodayCookeds.Add(toAdd);
product.Qty = product.Qty + todaycooked.QTY;
db.SaveChanges();
}
However, you can probably also get away with moving the db.SaveChanges() to outside of the loop, which would make the whole thing atomic (rather than risking getting the first 4 of 8 days saved, then an error):
...
for (var date = fd; date <= td; date = date.AddDays(1))
{
...
}
db.SaveChanges();

Update a List of values with empty string and keep value in other fields

I have a list in the form-
FieldName- DataType-
Date DateTime
DateString String
Unit double
Price double
I want to perform an operation such that if weakday on Date is not Monday then update DateString with empty string otherwise keep the value of DateString as it is.
Data is present in List.
UPDATE
I have applied aggregate function on DataTable dtGas as follows-
var qGas = from x in dtGas.AsEnumerable()
group x by new
{
Date = x.Field<DateTime>("Date"),
DateString = x.Field<string>("DateString")
} into egroup
select new
{
Date = egroup.Key.Date,
DateString = egroup.Key.DateString,
Unit = egroup.Sum(r => r.Field<double>("Unit")),
Price = egroup.Sum(r => r.Field<double>("Price"))
};
Now I need to show this result into Chart. Due to large amount of data values are overlapping on X-axis.
That is why I need to remove some values from DateString and show only few of them.
You can simply use conditional operator like this:-
group x by new
{
Date = x.Field<DateTime>("Date"),
DateString = x.Field<string>("DateString")
} into egroup
let isMonday = egroup.Key.Date.DayOfWeek.ToString() == "Monday"
select new
{
Date = egroup.Key.Date,
DateString = isMonday ? egroup.Key.DateString : "",
..other properties

assign values from table to Dhtmlx scheduler config

I'm a beginner with dhtmlx scheduler, I use dbfirst with mvc4 razor syntax.
So please can anybody help me to set the start time and endtime values I'm getting from the database:
here is my code:
controller:
sched.Config.first_hour = 8;
sched.Config.last_hour = 19;
public string GetDbValues()
{
string strState = "";
List<tblSettings> settings = new List<tblSettings>();
settings = _config.GetSettings();
var defaultState = from setting in settings
where (setting.Desc == "start time"
|| setting.Desc == "end time")
// starttime as 08 and end time as 20 from database
select setting.Settings;
foreach (var oState in defaultState)
{strState += oState + "|";
}
strState = strState.Remove(strState.Length - 1);
return strState;
}
I get the values for first_hour and last_hour as string from the output.
How to assign this string value to the first_hour and last_hour?
//I use linq to get the db values because of the table structure:
ID(int), Settings(nvarchar) ,Desc (nvarchar)
why do you concatenate the settings into string? More comprehensive data format will simplify the task. You could return List as it is and then just iterate it with foreach, applying needed settings. If for some reason you don't want to pass tblSettings objects, you can select data into Dictionary and then again, apply the values
var data = _config.GetSettings().ToDictionary(
s => s.Desc,
s => s.Setting,
StringComparer.Ordinal);
if(data.ContainsKey("start time"))
scheduler.Config.first_hour = int.Parse(data["start time"]);
if (data.ContainsKey("end time"))
scheduler.Config.first_hour = int.Parse(data["end time"]);

Date format in LINQ

i got problem with my LINQ to format date. Here is code
var resultCustomer = from row in formDg.dtCustomer.AsEnumerable()
where row.Field<int>("customerID") == customerID2
select new
{
name = row["customerName"].ToString(),
ic = row["customerIC"].ToString(),
add1 = row["customerAdd1"].ToString(),
add2 = row["customerAdd2"].ToString(),
tel = row["customerTel"].ToString(),
tel2 = row["customerTel2"].ToString(),
tel3 = row["customerTel3"].ToString(),
email = row["customerEmail"].ToString(),
dateRegister = row["customerDateRegister"].ToString(),
customerRef = row["customerRef"].ToString(),
customerGroup = row["groupCustName"].ToString(),
panelName = row["panelName"].ToString(),
};
var firstRecord = resultCustomer.First();// My record return single row only
My question is how i can format custom date like "dd/MM/yyyy" in customerDateRegister?, Because I got problem when my textbox show 16-Nov-12 12:00:00 AM. I don`t want to display time but just date only.
I have try like this tbDateRegOv.Text = firstRecord.dateRegister.ToString("dd/MM/yyyy");. not work. Then i try dateRegister = row["customerDateRegister"].ToString("dd/MM/yyyy"), in LINQ. Same problem.
So how can I solved this problem? Thanks for help. :)
You need to cast your row as a DateTime first. This will allow you to use the custom format strings for dates.
dateRegister = ((DateTime)row["customerDateRegister"]).ToString("dd/MM/yyyy")
If customerDateRegister is of type DateTime you should make it a DateTime in the first place. Therefor use the DataRow extension method Field<T>:
dateRegister = row.Field<DateTime>("customerDateRegister")
You could try this , replace your dateRegister line with this.
dateRegister = ((DateTime)row["customerDateRegister"]).ToString("dd/MM/yyyy"),
Or, you can use MaskedEditBox with the desired datetime mask

Linq XML query with nested loop - 1

In this question, if I need to get "date" included in the output, what changes should be made?
When I included
let dt = l.Element("Date").Value
It gives, "Object reference not set to an instance of an object"
var query = from l in doc.Descendants("L1")
let dt = l.Element("Date").Value
let id = l.Attribute("id").Value
from subject in l.Descendants("Subject")
select new
{
Date = dt,
Id = id,
SubjectName = (string)subject.Attribute("SubjectName"),
Score = (string)subject.Attribute("Score")
};
foreach (var result in query)
{
Console.WriteLine(result);
}
If l doesn't have an Date element, trying to access l.Element("Date").Value will incur an error. You can use a conditional:
var query = from l in doc.Descendants("L1")
let dt = l.Elements("date").Any()
? l.Element("date").Value
: AnyDefaultValueIWantForDate
let id = l.Attribute("id").Value
from subject in l.Descendants("Subject")
select new
{
Date = dt,
Id = id,
SubjectName = subject.Attribute("SubjectName").Value,
Score = subject.Attribute("Score").Value
};
(I also added the .Value in SubjectName and Score).
Looking at your other XML, it does not, as Mr. Skeet mentioned, have anything in the <date> elements. You will need to explicitly handle that if you aren't planning on always having data in there.
You can do something like this:
let dt = l.Element("date") == null ? string.Empty : l.Element("date").Value
Assuming l is not null then l.Element("Date") is null which would mean that one or more of your L1 elements does not have a child Date element.
The fix would depend on what you want to do with missing dates. If you want to use default(DateTime) as a "magic" date, you could do:
let dt = (l.Element("Date") == null ? default(DateTime) : l.Element("Date").Value)

Categories

Resources