This question already has answers here:
Best practices for serializing objects to a custom string format for use in an output file
(8 answers)
Closed 7 years ago.
I have a class, all string properties like this:
public class MyClass
{
public string Name {get;set;}
public string Phone {get;set;}
// a bunch of more fields....
{
And a list of that class List<MyClass> myListOfObjects; that I have populated it through out the program with values.
And then I have a file (csv) with headers:
Name, Phone, etc...
I want to write the contents of that myListOfObjects into that file.
I was thinking just loop through them and write one row per object. But wanted to see is there a better nicer way?
You can write all your data in one shot, like
var list = new List<MyClass>();
var fileData = list.Select(row => string.Join(",", row.Name, row.Phone, row.Etc)).ToArray();
File.WriteAllLines(#"C:\YourFile", fileData);
Note: This is one way to improve the file write, but it doesn't handle un-escaped text data like Name with comma.
Related
This question already has answers here:
Given a filesystem path, is there a shorter way to extract the filename without its extension?
(10 answers)
Closed 10 months ago.
Suppose I have an array of strings with full file names and paths. For example
string[] filesArray = Directory.GetFiles(#"C:\dir", "*", SearchOption.AllDirectories);
Now let's say we have the following data in the array:
filesArray[0] = "C:\dir\file1.txt"
filesArray[1] = "C:\dir\subdir1\file2.txt"
filesArrat[2] = "C:\dir\subdir1\subdir2\file3.txt"
... etc.
Now I want a new array, that will store only the files' names, something like this:
nameArray[0] = "file1.txt"
nameArray[1] = "file2.txt"
nameArray[2] = "file3.txt"
What is the best way to do it, using string array only, without storing the full FileInfo class objects?
Using LINQ it's pretty simple
string[] nameArray = filesArray.Select(p => Path.GetFileName(p)).ToArray()
This question already has answers here:
Read a XML (from a string) and get some fields - Problems reading XML
(5 answers)
Closed 12 months ago.
I have this XML file which I am having troubles deserializing it, so I'm going kind of way around it. I have an XML string and I want to get a value out of it. Let's say this is my XML string:
string XMLstring = "<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<InputText>123</InputText>
<InputText>Apple</InputText>
<InputText>John</InputText>
</note>";
Now, I have tried something like checking if the XMLstring contains InputText, but I want someway to get all the three values from there and then use them somewhere. Is there any way I can do this without having to deserialize it?
You can use LINQ-to-XML to parse the string and obtain the values.
using System.Linq;
using System.Xml.Linq;
public static void Main()
{
var xml = #"<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body><InputText>123</InputText><InputText>Apple</InputText><InputText>John</InputText></note>";
var list = XDocument.Parse(xml).Descendants("InputText").Select( x => x.Value );
foreach (var item in list) Console.WriteLine(item);
}
Output:
123
Apple
John
Fiddle
This question already has answers here:
How can I check if a string exists in another string
(10 answers)
Closed 5 years ago.
I'm working on a Existing Class file(.cs) which fetches a string with some data in it.
I need to check if the string contains a word. String has no blank spaces in it.
The string-
"<t>StartTxn</t><l>0</l><s>0</s><u>1</u><r>0</r><g>1</g><t>ReleaseUserAuthPending</t>"
I need to check if the string contains 'ReleaseUserAuthPending' in it.
You can try this:
var strValue = "<t>StartTxn</t><l>0</l><s>0</s><u>1</u><r>0</r><g>1</g><t>ReleaseUserAuthPending</t>";
if (strValue.Contains("ReleaseUserAuthPending"))
{
//Do stuff
}
Refer About String - Contains function
For your information: Contains function is case-sensitive. If you want to make this Contains function as case-insensitive. Do the following step from this link.
bool containsString = mystring.Contains("ReleaseUserAuthPending");
Try
String yourString = "<t>StartTxn</t><l>0</l><s>0</s><u>1</u><r>0</r><g>1</g><t>ReleaseUserAuthPending</t>";
if(yourString.Contains("ReleaseUserAuthPending")){
//contains ReleaseUserAuthPending
}else{
//does not contain ReleaseUserAuthPending
}
This question already has answers here:
How does one parse XML files? [closed]
(12 answers)
Closed 6 years ago.
I have the following XML structure for a card game. I want to load the card titels and descriptions into two arrays that I can use to randomize the cards.
<Cards>
<CardTitles>
<Title>Some Title</Title>
.
.
.
.
.
</CardTitles>
<CardDesc>
<Desc>Some description</Desc>
</CardDesc>
</Cards>
But no matter what I do or what code I write I'm unable to get the actual text from the proper tag. The closest I got was following this example :https://msdn.microsoft.com/en-us/library/system.xml.xmlreader.readsubtree(v=vs.110).aspx
I know I'm not supposed to ask for complete solutions but I'm just stumped. Any help in getting this matter cleared up to me will be great.
Supposing that you have an xml file named sample.xml in C:\temp you can use LINQ To XML:
XElement x = XElement.Load (#"c:\temp\Sample.xml");
IEnumerable<string> titles = from title in x.Element("CardTitles").Elements()
select title.Value;
IEnumerable<string> descriptions = from description in x.Element("CardDesc").Elements()
select description.Value;
Instead of going XmlReader route, you can use XmlSerializer which is much more simple and straightforward to use.
https://msdn.microsoft.com/en-us/library/58a18dwa(v=vs.110).aspx
You'd have something like this:
<Cards>
<CardTitles>
<Title>Some Title</Title>
</CardTitles>
<CardDesc>
<Desc>Some description</Desc>
</CardDesc>
</Cards>
.Net Classes
public class Cards {
public CardTitles CardTitles;
public CardDesc CardDesc;
}
public class CardTitles {
public String Title;
}
public class CardDesc {
public String Desc;
}
And then use XmlSerializer.Deserialize method.
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Cards));
StringReader inputStrReader = new StringReader(inputString);
Cards cards = (Cards)xmlSerializer.Deserialize(inputStrReader);
This question already has answers here:
Regex To Extract An Object From A JSON String
(3 answers)
Closed 8 years ago.
string sample = "{\"STACK_SIZE\":4,\"thes_stack\":[4,4]}";
how can I parse it using RE in C#?
First of all this isn't a valid JSON, remove the backslashes.
Second, using a library like JSON.NET you can parse your sample.
string sample = "{"STACK_SIZE":4, "thes_stack":[4,4]}";
var parsed = JsonConvert.DeserializeObject<dynamic>(sample);
that will parse it into a dynamic type, if you want something more strongly typed create your own class:
class StackInfo
{
public int STACK_SIZE {get; set;}
public int[] thes_stack {get; set;}
}
then you can deserialize into it:
string sample = "{"STACK_SIZE":4, "thes_stack":[4,4]}";
var parsed = JsonConvert.DeserializeObject<StackInfo>(sample);
But since you didn't put exactly what you need or exactly what your problem is with the suggestions in the comments no one can really help you.