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

How to pass the current index iteration inside a select new MyObject

这是我的代码:

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()
                         });

我需要 select new 中的当前 index 迭代。我在哪里传递它?

编辑 - 我当前的查询:

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; }
}

使用IEnumerable扩展方法,我觉得语法更直接。 您需要第二个重载,它接收 IEnumerable 项目和索引。

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

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

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

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

将数据源抽象为 x:

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

作为您的新问题的跟进... 这是一个带有自定义类型(例如您的 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
*/

重要:确保您要使用扩展方法的数据类型是 IEnumerable 类型(继承 IEnumerable),否则您将找不到此 Select 重载我的解决方案是讲,暴露。

你可以这样做:

let currIndex = collection.IndexOf(collectionItem)

您的代码将变为:

infoGraphic.chartData =

(from x in db.MyDataSource group x by x.Data.Value.Year into g

                         // Get Iterator Index Here
                         let currIndex = db.MyDataSource.IndexOf(x)

                         select new MyObject
                         {index = currIndex.ToString(), // Your Iterator Index
counter = g.Count()
                         });