简体   繁体   中英

How to collect values for all the keys from a Dictionary<string,object> in a List

I have a Dictionary<string, Data> collection.

My Data class is has multiple members.

public class Data
{
public string docid{get;set;}
public string filename{get; set;}
public string doctype{get;set;}
}

so, each key in the dictionary has a list of values. I want to write the values for all the keys in a csv file.

My csv file will have columns of

  • docid
  • filename
  • doctype

I have been using LINQ2CSV library for writing into csv, but since it accepts a list and a filepath as a parameter, i am not able to collect values for all the keys into a list. please suggest a better way to achieve this .

LINQ2CSV's Write method accepts IEnumerable<T> . Your Values in dictionary are available as an array. You can do:

cc.Write(yourDictionary.Values, "filePath.csv");

There is no need for getting List<Data> from Dictionary Values , but if you still want to create a List<Data> you can do:

List<Data> myList = yourDictionary.Values.ToList();

or

List<Data> myList = new List<Data>(yourDicitionary.Values);

您可以将字典的值复制到列表中:

var list = dictionary.Values.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