如何将数据分为具有不同值的单独列表C#? [英] how to group data into separate lists with distinct values c#?

查看:54
本文介绍了如何将数据分为具有不同值的单独列表C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据表,如下所示,

I have a datatable as below,

我有一项返回list的服务,

I have a service which returns list ,

我想使用linq将具有不同的rowid和字段名称的数据分组并将其放入 一个单独的列表.我该如何实现?

i want to group data with distinct rowid and field name using linq and put them in a separate lists. how can i achieve it?

这是我按ID分组的代码

here is my code for grouping by id

   var query = ae.Result.CommonDataValues.GroupBy(item => item.RowID)
                      .Select(g => g.Max(item => item.ID));

推荐答案

假设您要/拥有一个映射这些属性的类,例如:

Assuming that you want/have a class which maps these properties like:

public class Data
{
    public int ID { get; set; }
    public int RecordID { get; set; }
    public int RecordFieldData { get; set; }
    public int RowID { get; set; }
    public int FieldID { get; set; }
    public string FieldName { get; set; }
}

,并且您想要一个List<List<Data>>,其中每个唯一的RowID + FieldName组合都包含一个List<Data>,您可以GroupBy匿名类型:

and you want a List<List<Data>> which contains a List<Data> for every unique RowID+FieldName combination, you can GroupBy an anonymous type:

List<List<Data>> allData = data.AsEnumerable()
    .GroupBy(r => new { RowID = r.Field<int>("RowID"), FieldName = r.Field<string>("FieldName") })
    .Select(g => g
        .Select(r => new Data
        {
            RowID = g.Key.RowID,
            FieldName = g.Key.FieldName,
            FieldID = r.Field<int>("RowID"),
            ID = r.Field<int>("ID"),
            RecordFieldData = r.Field<int>("RecordFieldData"),
            RecordID = r.Field<int>("RecordID")
        })
        .ToList())
    .ToList();

如果要使用Dictionary代替,并以RowId + FieldName作为键:

If you want to use a Dictionary instead with the RowId + FieldName as key:

Dictionary<Tuple<int, string>, List<Data>> allData = data.AsEnumerable()
    .GroupBy(r => new { RowID = r.Field<int>("RowID"), FieldName = r.Field<string>("FieldName") })
    .ToDictionary(
        g => Tuple.Create(g.Key.RowID, g.Key.FieldName), 
        g => g.Select(r => new Data
            {
            RowID = g.Key.RowID,
            FieldName = g.Key.FieldName,
            FieldID = r.Field<int>("RowID"),
            ID = r.Field<int>("ID"),
            RecordFieldData = r.Field<int>("RecordFieldData"),
            RecordID = r.Field<int>("RecordID")
        })
        .ToList());

// lookup with RowId + FieldName, f.e.:
List<Data> datas;
if(allData.TryGetValue(Tuple.Create(1, "name"), out datas))
{
    // dictionary contains this data
}

这篇关于如何将数据分为具有不同值的单独列表C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆