flutter Sorting arraylist by Date - sorting

In My streamBuilder I have Array list contains dates having format(dd-MM-yyyy).
I want to arrange the list in ascending order.
The code I used in StreamBuilder after getting Datasnapshot
Map<dynamic, dynamic> data = snap.data.snapshot.value;
List item = [];
data.forEach(
(index, data) => item.add(
{"key": index, ...data}
)
);
item..sort((a,b)=>a['key'].compareTo(b['key']));
I am expecting result as
16-06-2020
17-06-2020
18-06-2020
19-06-2020
22-06-2020
04-07-2020
The result I am getting is
04-07-2020
16-06-2020
17-06-2020
18-06-2020
19-06-2020
22-06-2020

You'll need to parse your Strings to DateTimes. Since DateTime parse() method won't accept Strings in the format you provided, you can do something like this:
List<String> strings = ['04-07-2020', '17-06-2020', '16-06-2020', '19-06-2020', '18-06-2020', '22-06-2020'];
List<DateTime> dateTimes = [];
strings.forEach((string) {
var splitted = string.split('-');
var day = splitted[0];
var month = splitted[1];
var year = splitted[2];
var formatted = '$year-$month-$day';
dateTimes.add(DateTime.parse(formatted));
});
dateTimes.sort((a, b) => a.compareTo(b));
Just adapt it for your structure!

Storing the data as Timestamps in Firebase would make it much simpler, then you can sort it by this Timestamp.
If you need the dates formatted as a String (dd-MM-yyyy) you can just parse it to Datetime and use the Intl-Package to convert it to a formatted String.

Related

Javascript d3.timeParse returning null

I have a string like this:
"[\'2021_04_27__21_52_09\', \'2021_04_27__21_52_13\', \'2021_04_27__21_52_16\']",
and I separate out the date values and put them in an array like this:
["2021_04_27__21_52_09", "2021_04_27__21_52_13", "2021_04_27__21_52_16"].
I want to draw a line plot with these values on the x axis so I do
`var x_data = ["2021_04_27__21_52_09", "2021_04_27__21_52_13", "2021_04_27__21_52_16"]
var timeParser = d3.timeParse("%Y_%m_%d__%H_%M_%S");`
timeParser(x_data) returns null and I'm not sure why. How do I convert the x_data array into a format so that I can easily create d3 graph using the array as the x axis?
First test:
timeParser("2021_04_27__21_52_09")
If that works, you need to map the function across your array:
let x = x_data.map(timeParser)
Format your data strings correctly and convert to valid JS dates:
const data = ["2021_04_27__21_52_09", "2021_04_27__21_52_13", "2021_04_27__21_52_16"];
const converted = data.map(d => {
const date = d.substr(0, 10).replaceAll('_', "/");
const time = d.substr(12).replaceAll('_', ':');
return new Date(`${date} ${time}`);
});

How to remove from an List Object in c#

I have an Action method in my controller which returns a List Object
Public ActionResult GetCats(long Id,string strsortorder,string dltIds)
{
var Result=objrepo.GetCats(Id);//this method returns me List of Result
}
My array looks like this:
var Result=[{CatId:1015,CatName:Abc},{CatId:1016,CatName:Acd},
{CatId:1017,CatName:Adf},{CatId:1018,CatName:CDdf},{CatId:1019,CatName:asdas},
{CatId:1020,CatName:Abc},{CatId:1021,CatName:Abc},{CatId:1022,CatName:Abc},
{CatId:1023,CatName:Abc},{CatId:1024,CatName:Abc}]
What I want to do is:
Using two more parameters in my Action Method "strsortorder" and "dltIds"
that have a list of ids like this:
strsortorder="1021,1015,1016,1019,1022";
dltIds="1017,1018,1020";
From this the "Result" returned from my method , I want to remove the records which are in "dltids" and the remaining array should be sorted in the order which I have in "strsortorder";
In the end the new object should look like this:
var NewResult=[{CatId:1021,CatName:Abc},{CatId:1015,CatName:Abc},
{CatId:1016,CatName:Acd},{CatId:1019,CatName:asdas},{CatId:1022,CatName:Abc},
{CatId:1023,CatName:Abc},{CatId:1024,CatName:Abc}]
Can any one help me in acheiving this in linq or any other way?
I want to avoid any type of loop or froeach here for max extent, I know it can be done by looping but I want to avoid this since the result can sometimes contain large amounts of data.
I realized you can use an ArrayList instead of a Dictionary and it would be faster. I think Dictionary is clear how it works but here is the "better" implementation using array list:
var excludeList = dltIds.Split(",".ToCharArray());
ArrayList sortList = new ArrayList(strsortorder.Split(",".ToCharArray()));
var NewResult =
Result.Where(item => ! excludeList.Contains(item.CatId.ToString()))
.OrderBy(item => {
if (sortList.Contains(item.CatId.ToString()))
return sortList.IndexOf(item.CatId.ToString());
return sortList.Count;
});
Original answer below:
Public ActionResult GetCats(long Id,string strsortorder,string dltIds)
{
var Result=objrepo.GetCats(Id);//this method returns me List of Result
var excludeList = dltIds.Split(",".ToCharArray());
int orderCount = 0; // used in the closure creating the Dictionary below
var sortList = strsortorder.Split(",".ToCharArray())
.ToDictionary(x => x,x => orderCount++);
// filter
var NewResult =
Result.Where(item => ! excludeList.Contains(item.CatId.ToString()))
.OrderBy(item => {
if (sortList.ContainsKey(item.CatId.ToString()))
return sortList[item.CatId.ToString()];
return sortList.Count();
});
}
How this works:
First I create lists out of your comma separated exclude list using split.
This I create a dictionary with the key being the ordering ID and the value being an integer that goes up by one.
For the filtering I look to see if an item is in the exclude array before I continue processing the item.
I then do a sort on matching against the key and the dictionary and returning the value -- this will sort things in the order of the list since I incremented a counter when creating the values. If an item is not in the dictionary I return one more than the maximum value in the dictionary which must be the count of the items. (I could have used the current value of orderCount instead.)
Questions?

Using Variables for Column Names when Querying Parse.com Database

I have two Parse.com classes. I retrieve an array of values from Class1. The values are the names of the parse.com columns in Class2. After retrieving the desired object from Class2, I want to loop through getting the appropriate columns in Class2 like this:
Parse.initialize("KsUhcunt9PkSkvyRWXAeL", "ykLWdyBk6wAmOPC");
var CheckWait = Parse.Object.extend("CheckWait");
var query = new Parse.Query(CheckWait);
query.equalTo("objectId", "oMP9qf7MAj");
query.first({
success: function(object) {
$(".success").show();
var test = object.get("myArray[1]");
},
OK. So, if I replace myArray[1] with the appropriate column name, it retrieved the desired data. I tested the value contained in myArray[1] and it does contain the correct column name. If i set another variable = myArray[1] parse.com still returns "undefined".
If the contents of myArray[1] is a string "nickname", then the following are equivalent:
var nick1 = object.get("nickname");
var nick2 = object.get(myArray[1]);
The issue is that you passed the string "myArray[1]" instead of the expression myArray[1].

How can I get the last date from a list of dates in the database then compare it with the current date?

I’m trying to retrieve dates from the database then use it to compare with current date. How can I get the last date from a list of dates in the database then compare it with the current date? Here’s what I’ve tried but I get a exception: “LINQ to Entities does not recognize the method 'System.DateTime Last…”
var manageDate= from d in db.Enrollments.Select(da=>da.Date) select d;
var manageAssgnDate = from asgn in db.Enrollments.Select(asgn => asgn.Date) select asgn;
List<DateTime> newDate = manageDate.ToList();
I normally use lambdas:
// This gets the max date in the table
var manageDate = db.Enrollments.Max(da => da.Date);
Is this what you were asking for ?
Found a work-around:
var stdAssgn= from sa in db.Assignments where sa.StudentId==currentId select sa.Date;
var dt = stdAssgn.ToList().Last ();
String a = dt.ToString();
and to convert to DateTime if needed...
DateTime b=Convert.ToDateTime(a);

Group By Dates using Linq

What I have is a set of users with join dates and I want to use GoogleChartSharp to create a chart showing how many users have joined each month.
So I have this set of dates (US format) in a list:
01/01/2009
02/01/2009
02/12/2009
03/02/2009
03/12/2009
03/22/2009
Googlechartsharp requires me to do something like this:
string[] monthYears = new string[] { "01/2009", "02/2009", "03/2009"};
int[] number= new int[] {1,2,3};
LineChart chart = new LineChart(150, 150);
chart.SetData(data);
chart.SetLegend(monthYears);
string url = chart.GetUrl();
How do I utilize linq to get the list of dates into arrays required by google? Or is Linq even the right tool?
Sure, Linq is an ideal tool. The code below is an example. (I have specified the month in the dates so I don't have to use DateTime.ParseExact when setting up the input array).
DateTime[] dates =
{
DateTime.Parse("jan/01/2009")
,DateTime.Parse("feb/01/2009")
,DateTime.Parse("feb/12/2009")
,DateTime.Parse("mar/02/2009")
,DateTime.Parse("mar/12/2009")
,DateTime.Parse("mar/22/2009")
};
var datesGroupedByMonthYear = from date in dates
group date by date.ToString("MM/yyyy") into groupedDates
orderby groupedDates.First() ascending
select new { MonthYear = groupedDates.Key, Dates = groupedDates };
string[] monthYears = (from d in datesGroupedByMonthYear select d.MonthYear).ToArray();
int[] number = (from d in datesGroupedByMonthYear select d.Dates.Count()).ToArray();
Asusming those numvers are the number of times each month occurs. Then you could do something like this:
var numbers = from d in monthYears .Select(x => DateTime.Parse(x))
group d by d.Month into dg
select dg.Count();
That will give you an IEnumerable of the count for each. If you need it as an array it is not too hard to convert that to an array.

Resources