Generic List to CSV String - c#

I have a list that I want to write to a CSV string.
The examples I have found all seem to be for single item lists, mine has multiple items.
The code I currently have is;
private static string CreateCSVTextFile<T>(List<T> data, string seperator = ",") where T : ExcelReport, new()
{
var objectType = typeof(T);
var properties = objectType.GetProperties();
var currentRow = 0;
var returnString = "";
foreach (var row in data)
{
var currentColumn = 0;
var lineString = "";
foreach (var info in properties)
{
lineString = lineString + info.GetValue(row, null) + seperator;
currentColumn++;
}
if (seperator != "")
{
lineString = lineString.Substring(0, lineString.Count() - 2);
}
returnString = returnString + Environment.NewLine + lineString;
currentRow++;
}
return returnString;
}
But when the list is large this method takes a very long time to run.
The class my list is based on looks like;
internal class ClientMasterFile
{
public String COL1{ get; set; }
public String COL2{ get; set; }
public String COL3{ get; set; }
public String COL4{ get; set; }
public String COL5{ get; set; }
public String COL6{ get; set; }
public String COL7{ get; set; }
public String COL8{ get; set; }
public String COL9{ get; set; }
public String COL10{ get; set; }
public String COL11{ get; set; }
public String COL12{ get; set; }
}
Is there a faster way to do this using an advanced version of String.Join?
Thanks

Your method can be simplified using StringBuilder and string.Join.
Concatenating strings directly is slow and uses a lot of memory which is fine for small operations.
See: Does StringBuilder use more memory than String concatenation?
private static string CreateCSVTextFile<T>(List<T> data, string seperator = ",")
{
var properties = typeof(T).GetProperties();
var result = new StringBuilder();
foreach (var row in data)
{
var values = properties.Select(p => p.GetValue(row, null));
var line = string.Join(seperator, values);
result.AppendLine(line);
}
return result.ToString();
}
A more complete implementation for CSVs:
private static string CreateCSVTextFile<T>(List<T> data)
{
var properties = typeof(T).GetProperties();
var result = new StringBuilder();
foreach (var row in data)
{
var values = properties.Select(p => p.GetValue(row, null))
.Select(v => StringToCSVCell(Convert.ToString(v)));
var line = string.Join(",", values);
result.AppendLine(line);
}
return result.ToString();
}
private static string StringToCSVCell(string str)
{
bool mustQuote = (str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n"));
if (mustQuote)
{
StringBuilder sb = new StringBuilder();
sb.Append("\"");
foreach (char nextChar in str)
{
sb.Append(nextChar);
if (nextChar == '"')
sb.Append("\"");
}
sb.Append("\"");
return sb.ToString();
}
return str;
}
Using: escaping tricky string to CSV format

we use linqtocsv with some success
https://linqtocsv.codeplex.com
and here is some explanation
http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library

Related

read from csv to object[] C#

I am trying to read from a .csv file to an object array.
There are other solutions here that give solutions for lists but I cannot seem to make it work for me.
Object definition:
public class DTOClass
{
//declare data members
[DataMember]
public DateTime Date { get; set; }
[DataMember]
public string stock_symbol { get; set; }
[DataMember]
public double stock_price_open { get; set; }
[DataMember]
public double stock_price_close { get; set; }
[DataMember]
public double stock_price_low { get; set; }
[DataMember]
public double stock_price_high { get; set; }
[DataMember]
public double stock_price_adj_close { get; set; }
[DataMember]
public long stock_volume { get; set; }
[DataMember]
public string stock_exchange { get; set; }
}
Instance declaration:
private DTOClass[] _dTOs;
Filter method:
private List<DTOClass> FromCsv(string csvLine, List<DTOClass> rest)
{
DataTable _dt = new DataTable();
string[] values = csvLine.Split(',');
int j = _dt.Rows.Count;
for (int i = 0; i < j; i++)
{
DTOClass dto = new DTOClass();
dto.Date = Convert.ToDateTime(values[0]);
dto.stock_symbol = Convert.ToString(values[1]);
dto.stock_price_open = Convert.ToDouble(values[2]);
dto.stock_price_close = Convert.ToDouble(values[3]);
dto.stock_price_low = Convert.ToDouble(values[4]);
dto.stock_price_high = Convert.ToDouble(values[5]);
dto.stock_price_adj_close = Convert.ToDouble(values[6]);
dto.stock_volume = Convert.ToInt64(values[7]);
dto.stock_exchange = Convert.ToString(values[8]);
rest.Add(dto);
}
return rest;
}
Calling filter:
DTO = File.OpenText(Filename).ReadLine().Select(v => FromCsv(v.ToString(),
_restDto)).ToArray();
I need this to return to an object array because it then goes into a CollectionView on a datagrid.
But I keep getting this error:
"Cannot implicitly convert type 'System.Collections.Generic.List[]' to 'MBM.Services.DTOClass[]'"
I know that I'm obviously returning a list of a list, but I've tried other methods that are offered and I'm simply stumped.
I've also tried this:
private static DataTable GetDataTableFromCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
//csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return csvData;
}
Calling with:
DataTable csvData = GetDataTableFromCSVFile(Filename);
But this doesn't seem to return anything from the file.
Any help is appreciated, thanks.
One simple way will be to split the lines and select them into your new object.
var result = File.ReadAllLines("pathTo.csv")
.Select(line => line.Split(','))
.Select(x => new MyObject {
prop1 = x[0],
prop2 = x[1],
//etc..
})
.ToArray();
There's no point in recreating the wheel, Id just use CsvHelper, it has support for what you're doing in addition to handling malformed CSV's you can additionally set up mapping like so:
public sealed class MyClassMap : ClassMap<MyClass>
{
public MyClassMap()
{
AutoMap();
Map( m => m.CreatedDate ).Ignore();
}
}
Then you can get the object like so:
var csv = new CsvReader( textReader );
var records = csv.GetRecords<MyClass>();

Skip reading the first line of the csv file

I am a beginner in programming,It's really difficult for me to analyze and debug how to skip reading the first line of the csv file. I need some help.
I need my id to fill my combobox in my form that contains all
Id's.In order to not include the header in browsing and
displaying.I need to skip the first line.
public bool ReadEntrie(int id, ref string name, ref string lastname, ref
string phone, ref string mail, ref string website)
{
int count = 0;
CreateConfigFile();
try
{
fs = new FileStream(data_path, FileMode.Open);
sr = new StreamReader(fs);
string temp = "";
bool cond = true;
while (cond == true)
{
if ((temp = sr.ReadLine()) == null)
{
sr.Close();
fs.Close();
cond = false;
if (count == 0)
return false;
}
if (count == id)
{
string[] stringSplit = temp.Split(',');
int _maxIndex = stringSplit.Length;
name = stringSplit[0].Trim('"');
lastname = stringSplit[1].Trim('"');
phone = stringSplit[2].Trim('"');
mail = stringSplit[3].Trim('"');
website = stringSplit[4].Trim('"');
}
count++;
}
sr.Close();
fs.Close();
return true;
}
catch
{
return false;
}
}
#Somadina's answer is correct, but I would suggest a better alternative. You could use a CSV file parser library such as CSV Helpers.
You can get the library from Nuget or Git. Nuget command would be:
Install-Package CsvHelper
Declare the following namespaces:
using CsvHelper;
using CsvHelper.Configuration;
Here's how simple your code looks when you use such a library:
class Program
{
static void Main(string[] args)
{
var csv = new CsvReader(File.OpenText("Path_to_your_csv_file"));
csv.Configuration.IgnoreHeaderWhiteSpace = true;
csv.Configuration.RegisterClassMap<MyCustomObjectMap>();
var myCustomObjects = csv.GetRecords<MyCustomObject>();
foreach (var item in myCustomObjects.ToList())
{
// Apply your application logic here.
Console.WriteLine(item.Name);
}
}
}
public class MyCustomObject
{
// Note: You may want to use a type converter to convert the ID to an integer.
public string ID { get; set; }
public string Name { get; set; }
public string Lastname { get; set; }
public string Phone { get; set; }
public string Mail { get; set; }
public string Website { get; set; }
public override string ToString()
{
return Name.ToString();
}
}
public sealed class MyCustomObjectMap : CsvClassMap<MyCustomObject>
{
public MyCustomObjectMap()
{
// In the name method, you provide the header text - i.e. the header value set in the first line of the CSV file.
Map(m => m.ID).Name("id");
Map(m => m.Name).Name("name");
Map(m => m.Lastname).Name("lastname");
Map(m => m.Phone).Name("phone");
Map(m => m.Mail).Name("mail");
Map(m => m.Website).Name("website");
}
}
Some more details in an answer here.
To skip the first line, just replace the line:
if (count == id)
with
if (count > 0 && count == id)
MORE THOUGHTS ON YOUR APPROACH
Because you used the ref keyword, each line you read will override the previous values you stored in the parameters. A better way to do this is to create a class to hold all the properties of interest. Then, for each line you read, package an instance of the class and add it to a list. You method signature (even the return type) will change eventually.
From your code, the class will look like this:
public class DataModel
{
public string Name { get; set; }
public string LastName { get; set; }
public string Phone{ get; set; }
public string Mail { get; set; }
public string Website{ get; set; }
}
Then your method will be like this:
public IList<DataModel> ReadEntrie(int id, string data_path)
{
int count = 0;
CreateConfigFile();
var fs = new FileStream(data_path, FileMode.Open);
var sr = new StreamReader(fs);
try
{
var list = new List<DataModel>();
string temp = "";
bool cond = true;
while (cond == true)
{
if ((temp = sr.ReadLine()) == null)
{
cond = false;
if (count == 0)
throw new Exception("Failed");
}
if (count > 0 && count == id)
{
string[] stringSplit = temp.Split(',');
var item = new DataModel();
item.Name = stringSplit[0].Trim('"');
item.LastName = stringSplit[1].Trim('"');
item.Phone = stringSplit[2].Trim('"');
item.Mail = stringSplit[3].Trim('"');
item.Website = stringSplit[4].Trim('"');
// add item to list
list.Add(item);
}
count++;
}
return list;
}
catch
{
throw; // or do whatever you wish
}
finally
{
sr.Close();
fs.Close();
}
}

Insufficient Memory error being thrown

namespace Calendar
{
public partial class MainCalendar : Form
{
private JArray items;
private List<String> AMList = new List<String>();
private List<String> PMList = new List<String>();
private List<String> accessToCalendarFilepath = new List<String>();
private List<CalendarModel> people;
private List<List<CalendarModel>> managers = new List<List<CalendarModel>>();
private List<String> userSelection = new List<String>();
private bool authorizedAccess = false;
private String javaScriptFileContainingJSONObject = "";
public MainCalendar()
{
InitializeComponent();
var locationInformation = System.Environment.CurrentDirectory + Path.DirectorySeparatorChar + "location.json";
using (StreamReader file = File.OpenText(locationInformation))
using (JsonTextReader reader = new JsonTextReader(file))
{
JArray o = (JArray)JToken.ReadFrom(reader);
items = o;
}
foreach (var item in items.Children())
{
var itemProperties = item.Children<JProperty>();
// you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "name");
var myElementValue = myElement.Value; ////This is a JValue type
if(myElementValue.ToString().Contains("AM"))
{
AMList.Add(myElementValue.ToString());
}
if (myElementValue.ToString().Contains("PM"))
{
PMList.Add(myElementValue.ToString());
}
}
mondayAM.DataSource = AMList.ToArray();
tuesdayAM.DataSource = AMList.ToArray();
wednesdayAM.DataSource = AMList.ToArray();
thursdayAM.DataSource = AMList.ToArray();
fridayAM.DataSource = AMList.ToArray();
mondayPM.DataSource = PMList.ToArray();
tuesdayPM.DataSource = PMList.ToArray();
wednesdayPM.DataSource = PMList.ToArray();
thursdayPM.DataSource = PMList.ToArray();
fridayPM.DataSource = PMList.ToArray();
loadAccessControl("accesscontrol.json");
dateTimePicker1.AlwaysChooseMonday(dateTimePicker1.Value);
String dateSelected = dateTimePicker1.Value.ToShortDateString();
findManagerForSelectedDate(dateSelected);
}
public void loadAccessControl(String fileName)
{
var accessControlInformation = Environment.CurrentDirectory + Path.DirectorySeparatorChar + fileName;
List<AccessControl> accounts = JsonConvert.DeserializeObject<List<AccessControl>>(File.ReadAllText(accessControlInformation));
foreach (AccessControl account in accounts)
{
Console.WriteLine(account.accountName);
if (account.accountName.ToLower().Contains(Environment.UserName.ToLower()))
{
foreach (CalendarFile file in account.files)
{
// Console.WriteLine(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "content" + Path.DirectorySeparatorChar + file.Filename);
accessToCalendarFilepath.Add(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "content" + Path.DirectorySeparatorChar + file.Filename);
}
break;
}
}
contentsOfFile();
}
private void contentsOfFile()
{
String line;
foreach(var file in accessToCalendarFilepath)
{
StreamReader contentsOfJSONFile = new StreamReader(file);
while((line = contentsOfJSONFile.ReadLine()) != null)
{
if(line.Contains("var "))
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + "[";
}
else if(line.Contains("];"))
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + "]";
}
else
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + line;
}
}
people = JsonConvert.DeserializeObject<List<CalendarModel>>((string)javaScriptFileContainingJSONObject);
managers.Add(people);
javaScriptFileContainingJSONObject = "";
}
}
private void findManagerForSelectedDate(String dateSelected)
{
dateSelected = dateTimePicker1.Value.ToShortDateString();
List<String> managerNames = new List<String>();
foreach(var item in managers)
{
foreach (var subitem in item)
{
CalendarModel c = subitem;
Console.WriteLine(c.date);
c.name = new CultureInfo("en-US", false).TextInfo.ToTitleCase(c.name);
if (userSelection.Count > 0)
{
foreach (var addedUser in userSelection.ToArray())
{
if (!addedUser.Contains(c.name))
{
userSelection.Add(c.name); // CRASHING HERE
//{"Exception of type 'System.OutOfMemoryException' was thrown."}
}
}
}
else
{
userSelection.Add(c.name);
}
}
}
Console.WriteLine();
}
I keep running out of memory.
The CalendarModel class:
namespace Calendar
{
class CalendarModel
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("date")]
public string date { get; set; }
[JsonProperty("title")]
public string title { get; set; }
[JsonProperty("mondayAM")]
public string mondayAM { get; set; }
[JsonProperty("mondayPM")]
public string mondayPM { get; set; }
[JsonProperty("tuesdayAM")]
public string tuesdayAM { get; set; }
[JsonProperty("tuesdayPM")]
public string tuesdayPM { get; set; }
[JsonProperty("wednesdayAM")]
public string wednesdayAM { get; set; }
[JsonProperty("wednesdayPM")]
public string wednesdayPM { get; set; }
[JsonProperty("thursdayAM")]
public string thursdayAM { get; set; }
[JsonProperty("thursdayPM")]
public string thursdayPM { get; set; }
[JsonProperty("fridayAM")]
public string fridayAM { get; set; }
[JsonProperty("fridayPM")]
public string fridayPM { get; set; }
[JsonProperty("saturdayAM")]
public string saturdayAM { get; set; }
[JsonProperty("saturdayPM")]
public string saturdayPM { get; set; }
}
}
I keep crashing at
userSelection.Add(c.name)
Take a close look at what you are doing
foreach (var addedUser in userSelection.ToArray())
{
if (!addedUser.Contains(c.name))
{
userSelection.Add(c.name);
}
}
You are adding to userSelection in the userSelection loop
The test is on !addedUser.Contains
You should not even be able to do that but I think the ToArrray() is letting it happen
So you add Sally
Then then Mark
Then you add Mark again because in the loop Mark != Sally
You are not using List<String> managerNames = new List<String>();
private void findManagerForSelectedDate(String dateSelected)
{
dateSelected = dateTimePicker1.Value.ToShortDateString();
You pass in dateSelected, then overright with dateTimePicker1, and then you don't even use it
Most of you code makes very little sense to me

Variable declaration in the loop using Json

Here is my code in the controller.
public JsonResult directory()
{
List<string> alp = new List<string>();
var alp1 = new List<directories>();
string array = "";
int a = 0;
for (a = 0; a <= 25; a++)
{
int unicode = a + 65;
char character = (char)unicode;
string text1 = character.ToString();
string url1 = "<a href='/Directories/?search=" + text1 + "' 'rel=" + text1 + "'>";
string alpha = text1;
alp.Add(url1);
alphatxt.Add(alpha);
}
var alphaa = alp1.Add(new directories { arrary = url1, character = alphatxt });
return Json(alphaa, JsonRequestBehavior.AllowGet);
}
public class directories
{
public int a { get; set; }
public int unicode { get; set; }
public char character { get; set; }
public string[] arrary { get; set; }
}
Outputs are getting by
alp.Add(url1);
alp.Add(alpha);
How can i call these two outputs outside the loop.
so that i will get my output through the return
Json(alphaa, JsonRequestBehavior.AllowGet);
But I dont know how to declare the output to the variable outside the loop.
If you are trying to build a list of urls, one for each letter, then you can simply do something like:
public List<Directory> GetDirectories()
{
var dirs = new List<Directory>();
for (var ch = 'A'; ch <= 'Z'; ch++)
{
var url = string.Format(
"<a href='/Directories/?search={0}' rel='{0}'>", ch);
dirs.Add(new Directory() { Character = ch, Url = url });
}
return dirs;
}
// Directory class is simplifed a bit in this example
public class Directory
{
public char Character { get; set; }
public string Url { get; set; }
}
And then simply convert it to JSON in a separate method:
public JsonResult directory()
{
var dirs = GetDirectories();
return Json(dirs, JsonRequestBehavior.AllowGet);
}
Using LINQ, it could be simplified to:
private static readonly string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public List<Directory> GetDirectories()
{
return Alphabet
.Select(ch => new Directory() { Character = ch, Url = CreateUrl(ch) })
.ToList();
}
private string CreateUrl(char ch)
{
return string.Format("<a href='/Directories/?search={0}' 'rel={0}'>", ch);
}
The way your code looks right now, it doesn't seem like you need to create this list on the server side at all (you are transferring a bunch of almost equal hard-coded URLs, which can easily be created on the client side using JavaScript), so I presume there is some additional data you are transferring with this query?
You can access the JsonResult.Data property, but I don't really think that is what you need. I suggest to create a method that return the actual result, and inside your action you call that one and serialize it as JSON:
public JsonResult directory()
{
return Json(this.GetDirectories(), JsonRequestBehavior.AllowGet);
}
private List<directories> GetDirectories()
{
... // your original code
}
I tried in many ways, At last got idea to use this way,
Also My code is shown below.
public JsonResult directory()
{
List<string> alp = new List<string>();
var alp1 = new List<directories>();
string array = "";
int a = 0;
for (a = 0; a <= 25; a++)
{
int unicode = a + 65;
char character = (char)unicode;
string text1 = character.ToString();
string url1 = "<a href='/Directories/?search=" + text1 + "' 'rel=" + text1 + "'>";
string alpha = text1;
alp.Add(url1);
alp.Add(alpha);
alp1.Add(new directories { dirurl = url1, text = alpha });
}
return Json(alp1, JsonRequestBehavior.AllowGet);
}
public class directories
{
public string text { get; set; }
public string dirurl { get; set; }
}
}
}

Display returned value from Class method to Form

In Form GroupExmStart I am calling Foo method from Question class and storing all Questions in var questions and passing it to int Quiz method,how can I store this question in string[] so that i can Display My questions using DisplayQuestions(),I tried to convert it into string using string[] ab=questions.ToArray(); but it is not working , Is that conversion is not possible or Where i am going wrong ?
Form GroupExmStart
public partial class GroupExmStart : Form
{
public GroupExmStart(string GroupName, string DurationID)
{
InitializeComponent();
this.GrpID=GroupName;
TopiID=db.GetTopicIDForGroup(GrpID);
Question qsn = new Question();
string[] conf = db.GetConfiguration(Convert.ToInt16(DurationID)).Split('|');
var questions = qsn.Foo(TopiID, conf);
int z = Quiz(questions);
int count = 0;
timer1.Interval = Convert.ToInt16(conf[1]) * 1000;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
int Quiz(List<Question> questions)
{
var str = questions.ToArray();
foreach (var item in str)//I am not getting how do i do it Getting `item as namespaceName.Question`
{
}
return 0;
}
private void DisplayQuestion(string id, string Q, string OP1, string OP2, string OP3, string OP4)
{
label5.Text = Q;
radioButton12.Text = OP4;
radioButton11.Text = OP4;
radioButton10.Text = OP4;
radioButton9.Text = OP4;
}
}
}
Class Question
public class Question
{
public string Id { get; set; }
public string Text { get; set; }
public string Option1 { get; set; }
public string Option2 { get; set; }
public string Option3 { get; set; }
public string Option4 { get; set; }
public string AnswerOption { get; set; }
public int Marks { get; set; }
Random _random = new Random();
public IEnumerable<Question> GetQuestions(string topicId, int marks)
{
string sql = "select QID,Question,Opt1,Opt2,Opt3,Opt4,AnsOp,Marks from Questions where TopicID IN(" +
topicId + ") and Marks=" + marks;
var cmd = new OleDbCommand(sql,acccon);
var rs = cmd.ExecuteReader();
if (rs != null)
{
while (rs.Read())
{
yield return
new Question
{
Id = rs[0].ToString() + "~",
Text = rs[1].ToString() + "~",
Option1 = rs[2].ToString() + "~",
Option2 = rs[3].ToString() + "~",
Option3 = rs[4].ToString() + "~",
Option4 = rs[5].ToString() + "~",
AnswerOption = rs[6].ToString() + "~",
Marks = marks
};
}
}
}
public List<Question> Foo(string TopicId, string[] conf)
{
var totQsn = Convert.ToInt16(conf[0]);
var mark1qsn = Convert.ToInt16(conf[3]); //this variable contains number of question to be display of mark 1
var mark2qsn = Convert.ToInt16(conf[4]);
var mark3qsn = Convert.ToInt16(conf[5]);
var mark4qsn = Convert.ToInt16(conf[6]);
var mark1questionSet = GetQuestions(TopicId, 1).ToList();
var mark2questionSet = GetQuestions(TopicId, 2).ToList();
var finalQuestions = new List<Question>();
for (int i = 0; i < mark1qsn; i++)
{
var setIndex = _random.Next(mark1questionSet.Count);
finalQuestions.Add(mark1questionSet[setIndex]);
mark1questionSet.RemoveAt(setIndex);
}
for (int i = 0; i < mark2qsn; i++)
{
var setIndex = _random.Next(mark2questionSet.Count);
finalQuestions.Add(mark2questionSet[setIndex]);
mark2questionSet.RemoveAt(setIndex);
}
return finalQuestions;
}
}
int Quiz(List<Question> questions)
{
foreach (Question question in questions)
{
// do something with question
// question.Id, question.Text etc.. can access from here
}
return 0;
}
if you need to display the question you better override the ToString method of Question class as below
public class Question
{
public override string ToString()
{
// you can change this as you wish
return string.Formt("Id:{0}, Text :{1}", Id, Text);
}
then you can try below
int Quiz(List<Question> questions)
{
foreach (Question question in questions)
{
MessageBox.Show(question.ToString());
}
return 0;
}
Or you can use existing method as below with few modifications
int Quiz(List<Question> questions)
{
foreach (Question question in questions)
{
DisplayQuestion(question);
}
return 0;
}
private void DisplayQuestion(Question question)
{
label5.Text = question.Text;
radioButton12.Text = question.Option1;
radioButton11.Text = question.Option2;
radioButton10.Text = question.Option3;
radioButton9.Text = question.Option4;
}
Your problem is that
var str = questions.ToArray();
returns an array of type Question
Question[]
and not an array of type string.
You will have to create an overload for Question to output to string what you need.
Something like
public class Question
{
public override string ToString()
{
return Text;
}
....
This should allow you to do something like
foreach (var item in str)
{
string itemText = item.ToString();
}
Try this,
string _que = string.Empty;
foreach (var item in questions)
{
_que =Convert.toString(item.Text);
}
return 0;
Since Question is class and Text is one of its property so u can access it by its object.

Categories