问题
I can't figure out how to do the second part of this (the for/foreach) with a LINQ expressions and haven't found any similar examples with LINQ. rangeDays will be between about 5 and 200, and q1 is a list of MyClasses where RowID is about from 10000 to 25000, without gaps.
public class MyClass { public int RowID; public object otherData; }
PopulateRange(int rangeDays, List<MyClass> q1){
var q2 = (from a in q1
let Rows = new int[rangeDays]
select new {a.RowID, Rows }).ToList();
foreach(var a in q2)
{
for(int i = 0; i < rangeDays; i++)
{
a.Rows[i] = a.RowID + i;
}
}
Thanks in advance.
Update: I got this running with 2 linq statements as shown below (hopefully this is all runnable this time).
public List<MyClass> PopulateRange(int rangeDays, IQueryable<TheirClass> q1)
{
var q2 = (from a in q1
select new MyClass()
{ RowID = a.RowID, Rows = new int[rangeDays] }).ToList();
q2.ForEach(a => a.Rows = Enumerable.Range(0, rangeDays).
Select(i => i + a.RowID).ToArray());
return q2;
}
public class MyClass
{
public int RowID;
public int[] Rows;
}
public class TheirClass
{
public int RowID;
public int ID;
public string Symb;
public DateTime? EventTime;
public decimal? Value;
}
This is acceptable, but does anyone know why the following single statement throws a NotSupportedException "Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator." when I try to compile & run:
public List<MyClass> PopulateRange(int rangeDays, IQueryable<TheirClass> q1)
{
var q2 = (from a in q1
select new MyClass()
{ RowID = a.RowID, Rows = Enumerable.Range(0, rangeDays).
Select(i => i + a.RowID).ToArray() }).ToList();
return q2;
}
回答1:
A slight variation on Ani's answer:
var q2 = q1.Select(a => new { Rows = Enumerable.Range(a.RowID, rangeDays)
.ToArray(),
RowID = a.RowID });
Differences:
- When there's just a single select, I don't bother with query expression syntax
- Rather than using Range from 0 and then Select, I figured it would be easier to just start off at a.RowID :)
回答2:
I think q1
's type should actually be List<MyRowClass>
or similar (it certainly can't be a List<int>
).
You probably want:
var q2 = (from a in q1
select new
{
a.RowID,
Rows = Enumerable.Range(0, rangeDays)
.Select(i => i + a.RowID)
.ToArray()
}).ToList();
来源:https://stackoverflow.com/questions/4914638/linq-to-populate-a-range