简体   繁体   中英

how to convert a datatable to List<long,List<keyvaluepair<string,string>>> in C#

I have a datatable with three columns says, ID, Name and Value.

I want to convert this datatable into List<long,List<keyvaluepair<string,string>>> .

The only trick is ID is foreign ket from another table. so it could have repeatative values.

I want to do it in C#.

Thanks in advance.


no, not dictionaly.....actualy I have two classes says, definded as....

public class RunParameters
    {
        public long RunId { get; set; }
        public List<WorkflowParameter<string>> WorkflowParameters { get; set; }

        public RunParameters()
        {
            WorkflowParameters = new List<WorkflowParameter<string>>();
        }
    }

 public struct WorkflowParameter<T>
    {
        public string ParameterName
        { get; set; }
        public T ParameterValue
        { get; set; }
    }

I want to convert the datable into List.

I cannot use dictionary since I want to serialize the this List to send it across the network....

Group items in your query by ID and project each item from group to KeyValuePair :

(from r in table.AsEnumerable()
 group r by r.Field<long>("ID") into g
 select g.Select(i => new KeyValuePair<string, string>(
                      i.Field<string>("Name"), i.Field<string>("Value"))
         .ToList()).ToList()

Or completely with method syntax:

 table.AsEnumerable()
      .GroupBy(r => r.Field<long>("ID"))
      .Select(g => g.Select(r => new KeyValuePair<string, string>(
                          r.Field<string>("Name"), r.Field<string>("Value"))
                    .ToList())
      .ToList() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM