如何在select new MyObject中传递当前索引迭代

mar*_*zzz 4 .net c# linq iteration

这是我的代码:

infoGraphic.chartData = (from x in db.MyDataSource
                         group x by x.Data.Value.Year into g
                         select new MyObject
                         {
                             index = "", // here I need a string such as "index is:" + index
                             counter = g.Count()
                         });
Run Code Online (Sandbox Code Playgroud)

我需要当前的index迭代select new.我在哪里通过?

编辑 - 我目前的查询:

var test = db.MyData
            .GroupBy(item => item.Data.Value.Year)
            .Select((item, index ) => new ChartData()
            {
                index = ((double)(3 + index ) / 10).ToString(),
                value = item.Count().ToString(),
                fill = index.ToString(),
                label = item.First().Data.Value.Year.ToString(),
            }).ToList();

public class ChartData
{
    public string index { get; set; }
    public string value { get; set; }
    public string fill { get; set; }
    public string label { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Vev*_*rke 6

使用IEnumerable扩展方法,我认为语法更直接.你需要第二个重叠,它接收不可数项和索引.

infoGraphic.chartData.Select((item, index) => {
   //what you want to do here
});
Run Code Online (Sandbox Code Playgroud)

您想在chartData上应用分组,然后选择子集/在结果数据上生成投影?

您的解决方案应如下所示:

infoGraphic.chartData
    .GroupBy(...)
    .Select((item, index) => {
      //what you want to do here
});
Run Code Online (Sandbox Code Playgroud)

将dataSource抽象为x:

x.GroupBy(item => item.Data.Value.Year)
 .Select((item, index) => new { index = index, counter = item.Count() });
Run Code Online (Sandbox Code Playgroud)

作为新问题的后续跟踪......这是一个带有自定义类型的简单工作方案(如ChartData):

class Program
{
    static void Main(string[] args)
    {
        List<int> data = new List<int> { 1, 872, -7, 271 ,-3, 7123, -721, -67, 68 ,15 };

        IEnumerable<A> result = data
            .GroupBy(key => Math.Sign(key))
            .Select((item, index) => new A { groupCount = item.Count(), str = item.Where(i => Math.Sign(i) > 0).Count() == 0 ? "negative" : "positive" });

        foreach(A a in result)
        {
            Console.WriteLine(a);
        }
    }
}

public class A
{
    public int groupCount;
    public string str;

    public override string ToString()
    {
        return string.Format("Group Count: [{0}], String: [{1}].", groupCount, str);
    }
}

/* Output:
*  -------
*  Group Count: [6], String: positive
*  Group Count: [4], String: negative
*/
Run Code Online (Sandbox Code Playgroud)

重要说明:确保您要使用扩展方法的数据类型是IEnumerable类型(继承IEnumerable),否则您将无法找到我的解决方案正在讨论的Select过载,暴露.