How to dynamically create objects from a file? - c#

I'm reading in files such as this with multiple lines like this.
"title,name,something,something,something"
How would I dynamically create new objects with those variables
I am splitting it already -
while (!reader.EndOfStream)
{
lineFromFile = reader.ReadLine();
split = lineFromFile.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}
My class is called Modules. Just don't know how to do it dynamically since I don't know how many modules will be in the file ETC.

Create List<Module> and add all items read from your file there:
List<Module> modules = new List<Module>();
while (!reader.EndOfStream)
{
lineFromFile = reader.ReadLine();
split = lineFromFile.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var newModule = new Module();
newModule.Property1 = split[0];
newModule.Property2 = split[1];
// (...) //
modules.Add(newModule);
}
Or using LINQ:
var modules = (from line in File.ReadAllLines("fileName")
let parts = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
select new Module() {
Property1 = parts[0],
Property2 = parts[1],
Property3 = parts[2],
}).ToList();

Related

Convert csv file to json which has two colums in a row and has multiple lines

I have a csv file and in one row i have two columns with multiple values .I want to convert that as a list
Example:
CSV data
Id name parentid
1 sam 12-george
24-jennifer
Json Data
[{ id:1, name:sam, parentid:[{ id:12, name:george }, { id:24, name:jennifer }] } ]
class Program
{
const string CSV =
#"Id name parentid
1 sam 12-george
24-jennifer";
static void Main(string[] args)
{
var csvArray = new JArray();
// Split to lines
string[] lines = CSV.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
// Ignore header line
JArray currentParentArray = null;
for (int i = 1; i < lines.Length; i++)
{
string[] items = lines[i].Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (items.Length == 3)
{
var line = new JObject();
csvArray.Add(line);
line["id"] = int.Parse(items[0]);
line["name"] = items[1];
currentParentArray = new JArray();
line["parentid"] = currentParentArray;
ParseParentId(items[2], currentParentArray);
}
if (items.Length == 1 && currentParentArray != null)
ParseParentId(items[0], currentParentArray);
}
var ser = JsonSerializer.CreateDefault();
string json = csvArray.ToString();
Console.WriteLine(json);
Console.ReadKey();
}
static void ParseParentId(string parentId, JArray parentArray)
{
int idx = parentId.IndexOf("-");
string id = parentId.Substring(0, idx);
string name = parentId.Substring(1 + idx);
var obj = new JObject();
obj["id"] = int.Parse(id);
obj["name"] = name;
parentArray.Add(obj);
}
}
This C# source should work. The array of parentid is remembered between lines and added to if the next line contains only another parentid.
Add a Nuget reference to Newtonsoft.Json to compile.

Add a string to new List<string>(new string[] { });

How do you add a array of strings to a List?
string csv = "one,two,three";
string[] parts = csv.Split(',');
_MyList.Add(new ListObjects()
{
Name = tag.Name,
MyObjectList = new List<string>(new string[] { parts })
});
This works:
_MyList.Add(new ListObjects()
{
Name = tag.Name,
MyObjectList = new List<string>(new string[] { "one", "two", "three" })
});
But then this is hardcoded. Is it even possible to split a string by "," and then add those values to a List
Use the ToList() method to convert the Array to a List.
string csv = "one,two,three";
string[] parts = csv.Split(',');
_MyList.Add(new ListObjects()
{
Name = tag.Name,
MyObjectList = parts.ToList()
});
Well, parts is an array already, just pass it to the List's constructor:
string csv = "one,two,three";
string[] parts = csv.Split(',');
_MyList.Add(new ListObjects()
{
Name = tag.Name,
MyObjectList = new List<string>(parts)
});
You can just use ToList<TSource>() method to do this:
var List = csv.Split(',').ToList();
The easiest thing to do is simply to use string.split, followed by .ToList(), like so:
string csv = "one,two,three";
List<string> Strings = csv.Split(',').ToList();

Removing the helping words from sentence

I have made a simple program in which a phrase is written and it displays the videos matching individual word.Let say i entered "I go to school". Here it should eliminate word "to"from the sentence and return just three words.
Here is a code which i have tried yet!! It works fine but when i enter some phrase it removes the helping verb and besides it, it replaces an empty string which makes problem. Any suggestions please
Code
class MyPlayer
{
string complete_name;
string root;
string[] supportedExtensions;
string videoname;
public MyPlayer(string snt)
{
videoname = snt;
}
public List<VideosDetail> test()
{
complete_name = videoname.ToLower() + ".wmv";
root = System.IO.Path.GetDirectoryName(#"C:\Users\Administrator\Desktop\VideosFrame\VideosFrame\Model\");
supportedExtensions = new[] { ".wmv" };
var files = Directory.GetFiles(Path.Combine(root, "Videos"), "*.*").Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower()));
List<VideosDetail> videos = new List<VideosDetail>();
VideosDetail id;
bool flagefilefound = false;
foreach (var file in files)
{
id = new VideosDetail()
{
Path = file,
FileName = Path.GetFileName(file),
Extension = Path.GetExtension(file)
};
FileInfo fi = new FileInfo(file);
if (id.FileName == complete_name)
{
id.FileName = fi.Name;
id.Size = fi.Length;
videos.Add(id);
flagefilefound = true;
}
if (flagefilefound)
break;
}
if (!flagefilefound)
{
MessageBox.Show("no such video is available. ");
}
return videos;
}
}
private void play_Click(object sender, RoutedEventArgs e)
{
List<string> chk = new List<string>();
chk.Add("is");
chk.Add("am");
chk.Add("are");
chk.Add("were");
chk.Add("was");
chk.Add("do");
chk.Add("does");
chk.Add("has");
chk.Add("have");
chk.Add("an");
chk.Add("the");
chk.Add("to");
chk.Add("of");
string sen = vdo.Text;
List<string> tmp = new List<string>();
string[] split = sen.Split(' ');
foreach (var item in split)
{
tmp.Add(item);
}
foreach (var item in chk)
{
if( sen.Contains(item) )
{
int index = sen.IndexOf(item);
sen = sen.Remove(index,item.Length);
};
}
foreach (var i in tmp)
{
MyPlayer player = new MyPlayer(i);
VideoList.ItemsSource = player.test();
}
}
What you're actually doing is eliminating so called stop words, and, probably, creating bag of words:
private static HashSet<String> s_StopWords =
new HashSet<String>(StringComparer.OrdinalIgnoreCase) {
"is", "am", "are", "were", "was", "do", "does", "to", "from", // etc.
};
private static Char[] s_Separators = new Char[] {
'\r', '\n', ' ', '\t', '.', ',', '!', '?', '"', //TODO: check this list
};
...
String source = "I go to school";
// ["I", "go", "school"] - "to" being a stop word is removed
String[] words = source
.Split(s_Separators, StringSplitOptions.RemoveEmptyEntries)
.Where(word => !s_StopWords.Contains(word))
.ToArray();
// Combine back: "I go school"
String result = String.Join(" ", words);

I encountered System.IndexOutOfRangeException when loading a txt file

I am trying the load a txt file which is written under a certain format, then I have encountered System.IndexOutOfRangeException. Do you have any idea on what's wrong with my codes? Thank you!
txt.File:
P§Thomas§40899§2§§§
P§Damian§40726§1§§§
P=Person; Thomas=first name; 40899=ID; 2=status
here are my codes:
using (StreamReader file = new StreamReader(fileName))
{
while (file.Peek() >= 0)
{
string line = file.ReadLine();
char[] charSeparators = new char[] { '§' };
string[] parts = line.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (PersonId personids in PersonIdDetails)
{
personids.ChildrenVisualisation.Clear();
foreach (PersonId personidchildren in personids.Children)
{
personidchildren.FirstName = parts[1];
personidchildren.ID = parts[2];
personidchildren.Status = parts[3];
personids.ChildrenVisualisation.Add(personidchildren);
}
}
}
}
at parts[1] the exception was thrown.
You should check if parts have enough items:
...
string[] parts = line.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (PersonId personids in PersonIdDetails) {
personids.ChildrenVisualisation.Clear();
// Check if parts have enough infirmation: at least 3 items
if (parts.Length > 3) // <- Pay attention for "> 3"
foreach (PersonId personidchildren in personids.Children) {
//TODO: Check, do you really start with 1, not with 0?
personidchildren.FirstName = parts[1];
personidchildren.ID = parts[2];
personidchildren.Status = parts[3];
personids.ChildrenVisualisation.Add(personidchildren);
}
else {
// parts doesn't have enough data
//TODO: clear personidchildren or throw an exception
}
}
...
I'm given the impression that the actual file is not that big, so it might be useful to use File.ReadAllLines instead (the con is the you need to have the entire file in memory), which gives you all the lines.
Also, removing the lines which are either empty or just whitespace might be necessary.
foreach (var line in File.ReadAllLines(fileName).Where(l => !string.IsNullOrWhiteSpace(l))
{
char[] charSeparators = new char[] { '§' };
string[] parts = line.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (PersonId personids in PersonIdDetails)
{
personids.ChildrenVisualisation.Clear();
foreach (PersonId personidchildren in personids.Children)
{
personidchildren.FirstName = parts[1];
personidchildren.ID = parts[2];
personidchildren.Status = parts[3];
personids.ChildrenVisualisation.Add(personidchildren);
}
}
}
Change the first line to
using (StreamReader file = new StreamReader(fileName, Encoding.GetEncoding("iso-8859-1")));
Possible way to do it, It's just one solution between more solutions
using (StreamReader file = new StreamReader(fileName))
{
while (file.Peek() >= 0)
{
string line = file.ReadLine();
char[] charSeparators = new char[] { '§' };
string[] parts = line.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
foreach (PersonId personids in PersonIdDetails)
{
personids.ChildrenVisualisation.Clear();
foreach (PersonId personidchildren in personids.Children)
{
if(parts.Length > 3)//Only if you want to save lines with all parts but you can create an else clause for other lines with 1 or 2 parts depending on the length
{
personidchildren.FirstName = parts[1];
personidchildren.ID = parts[2];
personidchildren.Status = parts[3];
personids.ChildrenVisualisation.Add(personidchildren);
}
}
}
}
}

Best way get first word and rest of the words in a string in C#

In C#
var parameters =
from line in parameterTextBox.Lines
select new {name = line.Split(' ').First(), value = line.Split(' ').Skip(1)};
Is there a way to do this without having to split twice?
you can store the split in a let clause
var parameters =
from line in parameterTextBox.Lines
let split = line.Split(' ')
select new {name = split.First(), value = split.Skip(1)};
Sure.
var parameters = from line in parameterTextBox.Lines
let words = line.Split(' ')
select new { name = words.First(), words.skip(1) };
string Str= "one all of the rest";
Match m = Regex.match(Str,"(\w*) (\w.*)");
string wordone = m.Groups[1];
string wordtwo = m.Groups[2];
You might try this:
private Dictionary<string, string> getParameters(string[] lines)
{
Dictionary<string, string> results = new Dictionary<string, string>();
foreach (string line in lines)
{
string pName = line.Substring(0, line.IndexOf(' '));
string pVal = line.Substring(line.IndexOf(' ') + 1);
results.Add(pName, pVal);
}
return results;
}

Categories

Resources