Reputation: 11
private Map GetMinMaxDistanceShcoolData(Map MonitorsData)
{
var tempData = MonitorsData.MonitorsDataList;
if (tempData != null)
{
foreach (var monitor in tempData)
{
foreach (var tehsil in monitor.Tehsils)
{
var ordered = tehsil.Schools.OrderBy(x => x.Distance).ToList();
var min = ordered.FirstOrDefault();
var max = ordered.LastOrDefault();
ordered.ToList().Clear();
tehsil.Schools.ToList().Add(min);
tehsil.Schools.ToList().Add(max);
}
}
}
return null;
}
Before and After clearing the list the count of the list is same. Even when I am using the Remove() instead of Clear(), it is also not removing the list. Also the Add(min) and Add(max) is not working.
Upvotes: 0
Views: 4533
Reputation: 3603
It's working just fine, you're just calling one many ToList
ordered is a List, then you call ToList (creating a new List), then you clear that last List (not touching the first one).
What you wrote :
ordered.ToList().Clear();
Is the same as
var newlist = ordered.ToList();
newlist.Clear(); // of course this doesn't clear ordered
What you need to do is simply
ordered.Clear();
Upvotes: 3
Reputation: 221
hi you have a few issues here, try something like this.
foreach (var tehsil in monitor.Tehsils)
{
var ordered = tehsil.Schools.OrderBy(x => x.Distance).ToList();
if(!ordered.Any || ordered.Count < 3) continue;
var maxmin = new List<tehsil.Schools> { ordered.FirstOrDefault(), ordered.LastOrDefault() }
tehsil.Schools = maxmin;
}
Upvotes: 0
Reputation: 2111
Remove the ToList()
call before Clear()
var tempData = MonitorsData.MonitorsDataList;
if (tempData != null)
{
foreach (var monitor in tempData)
{
foreach (var tehsil in monitor.Tehsils)
{
var ordered = tehsil.Schools.OrderBy(x => .Distance).ToList();
var min = ordered.FirstOrDefault();
var max = ordered.LastOrDefault();
ordered.Clear();
tehsil.Schools.ToList().Add(min);
tehsil.Schools.ToList().Add(max);
}
}
}
Upvotes: 0
Reputation:
You're clearing the list created by .ToList()
ordered.ToList().Clear();
// .ToList() - Creates a new list.
// .Clear() - Clears the list that was created.
To clear a list use:
ordered.Clear();
// .Clear() - Clears the list called ordered.
Upvotes: 0
Reputation: 19790
You are doing the wrong thing. ToList creates a new List, therefore Ordered
is a new list, and you clear that, but not the orginal data.
ordered.ToList().Clear();
Also ordered
is already a list, calling ToList
is redundant
I think you meant to do this:
var ordered = tehsil.Schools.OrderBy(x => x.Distance).ToList();
var min = ordered.FirstOrDefault();
var max = ordered.LastOrDefault();
tehsil.Schools.Clear();
tehsil.Schools.Add(min);
tehsil.Schools.Add(max);
Upvotes: 0