how to add linq result to list with key - c#

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)) ...

Related

Cast object to int[]

I have a array (with type of Object) which I'm extracting from a System.Collections.ArrayList. And I'm now trying to cast this object to a int[] so i can use it to compare it with another int[].
Note: I'm currently using .Net Framework 7.0.0
var query = (from el in l
where el.ID_Seal_From != "" && el.ID_Seal_From != null
select new
{
conn = el.Conn_from,
seal = el.ID_Seal_From
}).ToList();
var query2 = (from el in l
where el.ID_Seal_To != "" && el.ID_Seal_To != null
select new
{
conn = el.Conn_to,
seal = el.ID_Seal_To
}).ToList();
var res = query.Concat(query2).ToList();
ArrayList arrLi = new();
List<int> indexOfEqualElements = new();
for (int i = 0; i < res.Count; i++)
{
for (int j = 0; j < res.Count; j++)
{
if (res[i].seal.CompareTo(res[j].seal) == 0)
{
indexOfEqualElements.Add(j);
}
}
if (Contains(arrLi, indexOfEqualElements.ToArray()) == -1) //to avoid multiple entries
{
arrLi.Add(indexOfEqualElements.ToArray());
}
indexOfEqualElements.Clear();
}
In the "contains" call I'm trying to compare the Elements. For this case i need to avoid, that two equal arrays get added to the list. Because afterwards i need this distinct dataset to continue
I'm sorry for not trying to understand all the code above, but you simply can cast all the values of an ArrayList to an IEnumerable like this:
var arrayList = new ArrayList(2)
{
1,
2
};
var integerEnumerable = arrayList
.Cast<int>();
Feel free to add an .ToArray(), if you like an int[] instead.
ArrayList is deprecated. If you wanted a list you should use List<int>. In this instance, it seems you actually need something like a HashSet<int>.
But to just get distinct elements you can simply use DistinctBy.
var query = (
from el in l
where el.ID_Seal_From != "" && el.ID_Seal_From != null
select new
{
conn = el.Conn_from,
seal = el.ID_Seal_From
});
var query2 = (
from el in l
where el.ID_Seal_To != "" && el.ID_Seal_To != null
select new
{
conn = el.Conn_to,
seal = el.ID_Seal_To
});
var res = query.Concat(query2).DistinctBy(el => el.seal);

How to call a local method from the linq query

In my web api i need to execute a method from linq query itself. My linq query code snippet belongs to method is shown below which calls local method to get required data.
var onlineData = (from od in db.RTLS_ONLINEPERSONSTATUS
let zoneIds = db.RTLS_PERSONSTATUS_HISTORY.Where(p => p.person_id == od.PERSONID).OrderByDescending(z => z.stime > startOfThisDay && z.stime < DateTime.Now).Select(z => z.zone_id).ToList()
let zoneIdsArray = this.getZoneList((zoneIds.ToArray()))
let fzones = zoneIdsArray.Select(z => z).Take(5)
select new OnlineDataInfoDTO
{
P_ID = od.PERSONID,
T_ID = (int)od.TAGID,
LOCS = fzones.ToList()
}
public int[] getZoneList(decimal[] zoneIdsArray)
{
int[] zoneIds = Array.ConvertAll(zoneIdsArray, x => (int)x);
List<int> list = zoneIds.ToList();
for (int c = 1; c < zoneIdsArray.Count(); c++)
{
if (zoneIdsArray[c] == zoneIdsArray[c - 1])
{
list.Remove((int)zoneIdsArray[c]);
}
}
return list.ToArray();
}
I am getting exception at let zoneIdsArray = this.getZoneList((zoneIds.ToArray())), is there any way to solve this problem. I got logic to solve my problem from this link(Linq query to get person visited zones of current day ), the given logic is absolutely fine for my requirement but i am facing problem while executing it.
One way to achieve that would be to perform the projection on the client instead of the underlying LINQ provider. This can be done by separating your query into 2 steps:
var peopleStatus =
from od in db.RTLS_ONLINEPERSONSTATUS
let zoneIds = db.RTLS_PERSONSTATUS_HISTORY
.Where(p => p.person_id == od.PERSONID)
.OrderByDescending(z => z.stime > startOfThisDay && z.stime < DateTime.Now)
.Select(z => z.zone_id)
.ToList()
select new
{
Person = od,
ZoneIds = zoneIds,
};
var onlineData =
from od in peopleStatus.ToList()
let zoneIdsArray = this.getZoneList((od.ZoneIds.ToArray()))
let fzones = zoneIdsArray.Select(z => z).Take(5)
select new OnlineDataInfoDTO
{
P_ID = od.Person.PERSONID,
T_ID = (int)od.Person.TAGID,
LOCS = fzones.ToList()
};

Foreach substitute in Linq

I have a query that I want to substitue the foreach with linq because the foreach is so slow
how can I write all this codein one query
this is my code:
ret = new List<ReportData>();
foreach (var item in Number)
{
string A = item.Substring(0, 11);
string B = item.Substring(14, 2);
string C = item.Substring(19, 11);
string D = item.Substring(33);
ret1 = (from a in Report
where a.A == A && a.B == B && a.C == C && a.D == D && Filter.Type.Contains(a.Y)
select new ReportData
{
X = a.X,
Y = a.Y,
});
if (ret1 != null && ret1.ToList().Count > 0)
{
ret.AddRange(ret1);
}
}
As already mentioned in the comments, LINQ will not make a foreach any faster; if you have to iterate the entire collection, then foreach will be faster than LINQ.
There is no need to check for null or if any results exists in the inner LINQ statement; just add the range since the LINQ query will return an Enumerable.Empty<ReportData> if nothing is returned from the query.
if (ret1 != null && ret1.ToList().Count > 0)
{
ret.AddRange(ret1);
}
// becomes
ret.AddRange(ret1);
Assumming Number is a collection of string, make sure there are no duplicates:
foreach (string item in Number.Distinct())
If Number is a large list, thousands of items or more, then consider using a Parallel.ForEach.
Linq will just enumerate the collection just like a foreach would, but you might see some benefit from a join:
var items = Number.Select( item => new {
A = item.Substring(0, 11),
B = item.Substring(14, 2),
C = item.Substring(19, 11),
D = item.Substring(33),
});
var ret = (from a in Report
join i in items
on new {a.A, a.B, a.C, a.D} equals new {i.A, i.B, i.C, i.D}
where Filter.Type.Contains(a.Y)
select new ReportData
{
X = a.X,
Y = a.Y,
});

Randomly Selected Data from Database with Constraints

I have created a MySQL Database with a vast number of products and their cost. I utilize EF6 to wrap the database.
Based on the given input, I need to generate at random, a correct selection that meets the described criteria.
For example:
10 Items, Total Value $25
I am at a loss as how to properly go about iterating through the database to produce the required results.
What I am currently doing seems terribly inefficent:
using (var db = new Database())
{
var packageSelected = false;
var random = new Random();
var minItemId = (from d in db.products select d.id).Min();
var maxItemId = (from d in db.products select d.id).Max();
var timer = new Stopwatch();
timer.Start();
Console.WriteLine("Trying to make package...");
while (!packageSelected)
{
var currentItems = new List<int>();
for (var i = 0; i <= 9; i++)
{
var randomItem = random.Next(minItemId, maxItemId);
currentItems.Add(randomItem);
}
decimal? packageValue = 0;
currentItems.ForEach(o =>
{
var firstOrDefault = db.products.FirstOrDefault(s => s.id == o);
if (firstOrDefault != null)
{
var value = firstOrDefault.MSRP;
packageValue += value;
}
});
if (!(packageValue >= 25) || !(packageValue <= 26)) continue;
packageSelected = true;
timer.Stop();
Console.WriteLine("Took {0} seconds.", timer.Elapsed.TotalSeconds);
currentItems.ForEach(o =>
{
var firstOrDefault = db.products.FirstOrDefault(s => s.id == o);
if (firstOrDefault != null)
Console.WriteLine("Item: {0} - Price: ${1}", firstOrDefault.DESCRIPTION,
firstOrDefault.MSRP);
});
}
}
What about something like this:
public virtual TEntity GetRandom()
{
return DBSet.OrderBy(r => Guid.NewGuid()).Take(1).First();
}
public List<TEntity> Random(int amount, int maxprice)
{
var list = new List<TEntity>();
var tempPrice = 0;
for (int i = 0 ; i < amount; i++)
{
var element = GetRandom();
tempPrice += element.Price;
if (tempPrice > maxprice)
{
return list;
}
list.Add(element);
}
return list;
}
hope this helps
EDIT: If the maxprice is reached before the required amount of elements, the for-loop will stop and you won't get the full amount of elements.

How to remove repeating code in this method?

private static Game[] getMostPlayedGamesDo(int Fetch, int CategoryID)
{
Game[] r;
using (MainContext db = new MainContext())
{
if (CategoryID == 0)
{
var q = db.tblArcadeGames.OrderByDescending(c => c.Plays).Take(Fetch);
r = new Game[q.Count()];
int i = 0;
foreach (var g in q)
{
r[i] = new Game(g);
i++;
}
}
else
{
var q = db.tblArcadeGames.Where(c=>c.CategoryID == CategoryID).OrderByDescending(c => c.Plays).Take(Fetch);
r = new Game[q.Count()];
int i = 0;
foreach (var g in q)
{
r[i] = new Game(g);
i++;
}
}
}
return r;
}
I can't seem to define q outside the scope of the if, and I can't insert the returned values to the array outside the scope of the if! Not sure how to remove repeating code in this simple instance?
It's not clear what the type of q is -- but deducing from your usage:
db.tblArcadeGames.OrderByDescending(...)
Presumably it's an entity class from Linq-To-Sql or Entity Framework. In that case, you do have a concrete entity defined, presumably named tblArcadeGame. Therefore, move q out of the scope by not using var:
IQueryable<tblArcadeGame> q;
if (CategoryID == 0)
{
q = db.tblArcadeGames.OrderByDescending(c => c.Plays).Take(Fetch);
}
else
{
q = db.tblArcadeGames.Where(c=>c.CategoryID == CategoryID).OrderByDescending(c => c.Plays).Take(Fetch);
}
r = new Game[q.Count()];
int i = 0;
foreach (var g in q)
{
r[i] = new Game(g);
i++;
}
As you can see, the repeated code is now seen only once.
P.S. Tools like ReSharper are fantastic for this sort of thing. Using it, with one keystroke you can toggle between the var version and that using explicitly named types.
You should really just explicitly type q. But this may let you get away without it (ternary operator will enforce it for you).
var q = CategoryID == 0 ? db.tblArcadeGames.OrderByDescending(c => c.Plays).Take(Fetch)
: db.tblArcadeGames.Where(c=>c.CategoryID == CategoryID).OrderByDescending(c => c.Plays).Take(Fetch);
r = new Game[q.Count()];
int i = 0;
foreach (var g in q)
{
r[i] = new Game(g);
i++;
}
I assume q is type IQueryable.
private static Game[] getMostPlayedGamesDo(int Fetch, int CategoryID)
{
var q = db.tblArcadeGames;
if (CategoryID != 0)
{
q = q.Where(c => c.CategoryID == CategoryID);
}
q = q.OrderByDescending(c => c.Plays).Take(Fetch);
return q.Select(g => new Game(g)).ToArray();
}
List<tblArcadeGame> q;
/* object q; */
if (CategoryID == 0)
{
q = db.tblArcadeGames.OrderByDescending(c => c.Plays).Take(Fetch).ToList();
}
else
{
q = db.tblArcadeGames.Where(c=>c.CategoryID == CategoryID).OrderByDescending(c => c.Plays).Take(Fetch).ToList();
}
r = new Game[q.Count()];
int i = 0;
foreach (var g in q)
{
r[i] = new Game(g);
i++;
}
I'll assume q is List<tblArcadeGame>

Categories

Resources