Date Time Query

Miko Kagemori 46 Reputation points
2021-06-01T17:39:26.873+00:00

Can someone tell me how I can do a DateTimeQuery with LINQ and compare the dates?
I tried it like this:

private readonly string PATH = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "weatherdata.xml");

public List<WeatherData> weatherData(DateTime date1, DateTime date2)
{
List<WeatherData> list = new List<WeatherData>();

        if (date1 <= date2)
        {

            XElement xml = XElement.Load(PATH);

            var query = from data in xml.Elements("measurment")
                        where DateTime.Compare(DateTime.Parse(data.Element("date").Value), date1) >= 0 && DateTime.Compare(DateTime.Parse(data.Element("date").Value), date2) <= 0      //DateTime.Parse(xml.Element("date").Value) >= date1 && DateTime.Parse(xml.Element("date").Value) <= date2
                        select data;

            if (query.Any())
            {
                foreach (var w in query)
                {
                    WeatherData tmp = new WeatherData();
                    tmp.Temperature = w.Element("temperature").Value;
                    tmp.Humidity = w.Element("humidity").Value;
                    list.Add(tmp);
                }
            }
            else
            {
                WeatherData errorData = new WeatherData();
                errorData.Error = "Its wrong.";
                list.Add(errorData);
            }
        }
        else
        {
            WeatherData error = new WeatherData();
            error.Error = "No";
            list.Add(error);
        }

        return list;
    }

My Querry does not have any funcionality somehow and I don't know what to do...

Developer technologies | C#
{count} votes

Accepted answer
  1. SuchenderFarn17 81 Reputation points
    2021-06-01T17:44:34.76+00:00

    Add this to your Code:
    101379-grafik.png

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. alf 1 Reputation point
    2021-06-01T18:15:57.63+00:00

    A standard LINQ Query consists of the following

    var query = from <name> in <yourLoadedXMLFile>.Elements("YourXMLObject")
    where <name>.Element("AnyPropertyOfYourObject").Value.Contains(yourVariableYouWantToCompare)
    select <name>.Element("ThePropertyYouWantToGetSpittenOut");

    Here you want something that is written in that XML File that you want get out, f.e. you want your Temperatures out for the date you want, you compare for the date and then give out any temperatures for that date you just searched

    Kind regards Alf

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.