c# - 如何在选择的新 MyObject 中传递当前索引迭代

标签 c# .net 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()
                         });

我需要 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
});

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

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

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 重载,暴露。

关于c# - 如何在选择的新 MyObject 中传递当前索引迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31427452/

相关文章:

c# - Unity C# 可滚动 GUI.BOX 不适用于 android

c# - 使用 jQuery 驱动的双向数据绑定(bind) "Chosen"下拉

c# - 返回值的子表达式

c# - JQuery 数据表服务器端列集合

c# - 使用 where 语句的 LINQ 非常慢

c# - 在 linq 中使用包含

c# - DataContext 类是特定于 SQL Server 的吗?

c# - 为什么 TPL 不支持状态过滤的多任务延续?

c# - 无法使用 Microsoft.Office.Interop.Excel 加载文件或程序集“office,版本 = 15.0.0.0”

.net - 除了使用 List.Single 获取具有主键的元素之外,还有其他选择吗?