I want to store the result of the query called by the controller in a variable
public ActionResult Index()
{
Session["dateDebut"] = DateTime.Now.AddMonths(-1).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Session["dateFin"] = DateTime.Now.AddDays(0).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
HostClassReq hostClassChart = new HostClassReq();
Chart_Event cex = new Chart_Event();
var viewModel = new Chart_Event
{
chartVM = hostClassChart.callHostClass()
};
return View(viewModel);
}
Here is the methode callHostClass implementation
public Highcharts callHostClass()
{
DateTime begin = DateTime.ParseExact(HttpContext.Current.Session["dateDebut"].ToString(), "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
DateTime end = DateTime.ParseExact(HttpContext.Current.Session["dateFin"].ToString(), "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture).AddDays(1);
CreateChart createChart = new CreateChart();
List<String> xs = new List<string>();
var maListe = (from p in db.exclure
where (p.type.Contains("Host Class"))
group p by p.libelle into g
select new
{
libellex = g.Key
}).ToList();
List<string> strListe = new List<string>();
foreach (var x in maListe.Select(i => i.libellex))
{
strListe.Add(x.ToString());
}
var myList = (from p in db.Full
where ( (p.date_reception > begin & p.date_reception < end & !p.mc_host_class.Contains("NULL")) &
(!strListe.Contains(p.mc_host_class)))
group p by p.mc_host_class into g
orderby g.Count() descending
select new
{
hostclassx = g.Key,
countx = g.Count()
}).Take(10).ToList();
// HttpContext.Current.Session["allList"] = myList;
List<Full> questions = (List<Full>)HttpContext.Current.Session["allList"];
// questions = List <Full> myList;
foreach (var x in questions)
{
}
object[] ys = myList.Select(a => (object)a.countx.ToString()).ToArray();
foreach (var x in myList.Select(i => i.hostclassx))
{
if (x.Length > 20)
{
xs.Add((x.Substring(0, 20)));
}
else
{
xs.Add(x);
}
}
var chart = createChart.createChartBar(xs, ys, 10);
return chart;
}
I need to store the result of myList query in a variable that will be accessed by another classes i need some help.
Are you looking for this?
Session["yourName"]=myList;
EDIT After question edit emerged that he wanted to use session in a class not extending Controller.
NEW PART
Therefore you can't use the initial suggestion but instead include System.Web using System.Web; and use
HttpContext.Current.Session["yourName"]=myList;
When you have to get it you use
var yourList = (myListType)Session["yourName"];
if you are in a class extending Controller or
var yourList = (myListType)HttpContext.Current.Session["yourName"];
otherwise.
Try this:
HttpContext.Current.Session["name"] = mylist;
But be careful accessing session like that, might cause null-ref exceptions
Related
I have this class where the query must result in this list a property.
This property must check on table how many duplicated exists.
This code works, but its very slow. can you help me ?
var lst = _uow.Repository.GetAll();
var query =
from p in lst
select new GetRfqResponse
{
ID = p.ID,
//bad performance
Count = lst.Where(x => x.Property == p.Property).AsQueryable().Count(),
//
};
Counting in a queryable list can be easily achieved using the Count() function:
// Find duplicated names
var byName = from s in studentList
group s by s.StudentName into g
select new { Name = g.Key, Count = g.Count() };
Check this fiddle to see it running.
Below is for InMemory
GroupBy should come to help.
var propertyGroupedList = list.GroupBy(l=>l.Property);
var query = list.Select(l => new GetRfqResponse{
Id = l.Id,
Count = propertyGroupedList.First(g=> g.Key == l.Property).Count()
});
Or you can create a dictionary with key as "Property" and value as count, then you will have to loop just once to store the count.
This allows you to get count in constant time
Dictionary<string, int> map = new Dictionary<string, int>();
foreach (var item in lst)
{
if (!map.ContainsKey(lst.Property))
{
map.Add(item.Property, 1);
}
else
map[item.Property]++;
}
var z = lst.Select(l => new GetRfqResponse{
Id = l.ID,
Count = map[l.Property]
});
I have a linq which is inside a for loop,im adding the results to a list using addRange() but it will add whole thing in a single set,for example my first loop result has 16 items,the second has 10 items,...i want them to be added to list like this then i can see in list how many and which items has been added on each query
public List<statisticsDaily> dailyStat(List<string> id,string dtFrom,string dtTo)
{
List<StatisticsDaily> rsltofquery = new List<StatisticsDaily>();
for (int i = 0; i < id.Count; i++)
{
var rslt = (from d in db.statDaily
join s in db.masterData on d.m_turbine_id equals s.m_turbine_id
where d.m_turbine_id == IPAddress.Parse(id[i]) && d.m_date >= frm && d.m_date <= to
select new StatisticsDaily
{
m_wind_speed = d.m_wind_speed,
Date = d.m_date.ToString("yyyy-MM-dd"),
name = s.turbine_name,
Production = d.m_energy_prod,
Availability = d.m_corrected_av
}
).AsEnumerable().OrderBy(s => s.Date).ToList();
rsltofquery.AddRange(rslt);
}
You need to have collection of collections like List<List<StatisticsDaily>>.
So yours code will be:
public List<List<statisticsDaily>> dailyStat(List<string> id,string dtFrom,string dtTo)
{
List<List<StatisticsDaily>> rsltofquery = new List<List<StatisticsDaily>>();
for (int i = 0; i < id.Count; i++)
{
var rslt = (from d in db.statDaily
join s in db.masterData on d.m_turbine_id equals s.m_turbine_id
where d.m_turbine_id == IPAddress.Parse(id[i]) && d.m_date >= frm && d.m_date <= to
select new StatisticsDaily
{
m_wind_speed = d.m_wind_speed,
Date = d.m_date.ToString("yyyy-MM-dd"),
name = s.turbine_name,
Production = d.m_energy_prod,
Availability = d.m_corrected_av
}).AsEnumerable().OrderBy(s => s.Date).ToList();
rsltofquery.Add(rslt);
}
}
If you want to use all elements, not in parts, you can use SelectMany:
var x = dailyStat(id, dtFrom, dtTo);
foreach (var e in x.SelectMany(d => d)) ...
I would like to take, from a list, a group of elements which have the same field (direction field - look to code), and then take first item which occurs in list (myList order), checking if it is ok with if and take it.
Next, I want to take next direction (if exist), create a group and again take first element.
I don't know how many groups it will be at any step. I just know it will be max 4 group. How can I do this?
List <myClass> myList = allCreatedObjects;
class myClass
{
Control c;
Direction d;
}
public enum Direction
{
up, down, right, left,
}
I'm not sure what you want exactly. but if you want to group by direction, then in each direction check some condition, you may try as following:
var output = new Dictionary<Direction, List<myClass>>();
foreach (myClass cls in myList)
{
//check some condition based on cls properties
if (cls.c is TextBox && cls.d != Direction.down)
{
output[cls.d].Add(cls); //add it to output
}
}
//each item in output[direction] is of type List<myClass>
var upList = output[Direction.up]; //this is as List<myClass>
//var downList = output[Direction.down]; //this is as List<myClass>
//...
You could use linq, for example to select right:
var rightGroup = myList.Where(c => c.d == Direction.right);
If you want to do this automatically for all the enum values, you can use a loop like:
foreach (Direction direction in Enum.GetValues(typeof(Direction)))
{
var groupList = myList.Where(c => c.d == direction);
}
This will result in a couple of variables.
You can also use linq like this:
var group = from item in myList
group item by item.d into g
select new { key = g.Key, listItems = g.ToList() };
This will result in an object, with the direction as key, and listItems filled with the items. If you want empty lists for the non-added directions you'll need to join with the direction enum.
As for a more exotic example:
var group = from item in myList
where item.d == Direction.left //some condition on item
group item by item.d into g
where g.Any(c => c.d == Direction.up) //some condition on the group
select new { key = g.Key, values = g.ToList() };
List<myClass> myList = new List<myClass>
{
new myClass(){c = new Button(), d = Direction.down },
new myClass(){c = new Button(), d = Direction.left },
new myClass(){c = new Button(), d = Direction.right },
new myClass(){c = new Button(), d = Direction.up },
new myClass(){c = new TextBox(), d = Direction.down },
new myClass(){c = new TextBox(), d = Direction.left },
new myClass(){c = new TextBox(), d = Direction.right },
new myClass(){c = new TextBox(), d = Direction.up },
};
public class myClass
{
public Control c;
public Direction d;
}
public enum Direction
{
up, down, right, left,
}
private void button1_Click(object sender, EventArgs e)
{
var groups = myList.GroupBy(my => my.d);
var firstElems = groups.Select(g => g.FirstOrDefault()).ToList();
}
I have a method for parsing XML:
public static List<Profile> Parse XML(string Document)
{
List<Profile> Result = new List<Profile>();
doc = XDocument.Load(Document);
Resoults = (from n in doc.Descendants("level")
select new Profile()
{
CurrentID = int.Parse(n.Attribute("CurrentID").Value),
Location = (from l in n.Element("ID").Elements("ID")
select new Location()
{
id = (int)(l.Attribute("id")),
x = (Single)l.Attribute("x"),
y = (Single)l.Attribute("y"),
z = (Single)l.Attribute("z")
}).ToList(),
Bank = (from l in doc.Descendants("Banker")
select new Banker()
{
BankID = (int)(l.Attribute("id")),
BankX = (Single)(l.Attribute("x")),
BankY = (Single)(l.Attribute("y")),
BankZ = (Single)(l.Attribute("z"))
}).ToList(),
Vendor = (from l in doc.Descendants("Vendor")
select new Vendor()
{
VendorID = (int)(l.Attribute("id")),
VendorX = (Single)(l.Attribute("x")),
VendorY = (Single)(l.Attribute("y")),
VendorZ = (Single)(l.Attribute("z"))
}).ToList()
}).ToList();
var ProperID = Resoults.Where(s => s.CurrentID <= 10).Aggregate((c, d) => c.CurrentID > d.CurrentID ? c : d);
return ProperID; //error: Here i want to return list ProperID
}
I want to parse XML file and then get node out of parsed list with specific CurrentID.
I want to return ProperID list but compiler errores out with:
Cannot implicitly convert type 'Classes.XMLprofile.Profile' to 'System.Collections.Generic.List<Classes.XMLprofile.Profile>'
You want return Results that have proper id in CurrentId,
In code you got compiler error because of return value is a Profile object and method signature is a List of Profile objects, So:
return Resoults.Where(p=>p.CurrentID ==ProperID.CurrentID).ToList();
I have this data structure:
class Conference
{
private List<List<string>>_orgs;
public List<List<string>> Orgs
{
set { _orgs = value; } get { return _orgs; }
}
}
Data in this collection:
List<string> sublist = new List<string>();
sublist.Add("university");
sublist.Add("organization");
List<List<string>> list = new List<List<string>>();
list.Add(sublist);
Then:
Conference c = new Conference();
c.Orgs = list;
I have collection of conference objects:
List<Conference> listConferences = new List<Conference>();
listConferences.Add(c);
I want search a string like "uni" and find collection of conference have orgs like "uni". How can I do this?
You can do this:
var selection = listConferences
.Where(x => x.Orgs.SelectMany(y => y).Any(y => y.Contains("uni")))
.ToList();
Note:
the trailing ToList() might not be necessary depending on your needs (e.g. if you iterate selection only once you can skip it).
Please use this code, below;
instead of third one, you may use your own conference list. you can now use similar to like keyword.
List<string> first = new List<string>();
first.Add("University");
first.Add("Standard");
List<List<string>> second = new List<List<string>>();
second.Add(first);
List<List<List<string>>> third = new List<List<List<string>>>();
third.Add(second);
var e = third.Find(delegate(List<List<string>> r)
{
bool isValid = false;
if(r.Count > 0)
{
foreach(List<string> s in r)
{
if(s.Count > 0 )
{
isValid = s.FindAll(delegate(string t){ return t.StartsWith("uni", StringComparison.OrdinalIgnoreCase);}).Count > 0;
}
}
}
return isValid;
});
Done, one more workout using linq. You should be feeling comfortable with this:
var univ = from p in c.Orgs
select p.FindAll(r => r.FindAll(s => s.StartsWith("univ", StringComparison.OrdinalIgnoreCase)));