How to concatenate values in to a comma seperated values in c# - c#

I am reading text file where I would like to get values based on condition. First I will take FREQ where CELLID = 639 and ISMAINBCCH=YES,that I have done now next task is I have to concatenate FREQ values in a comma separated way where CELLID=639 and ISMAINBCCH=NO, so the output I want is 24,28,67. How to achieve that?
lines are
ADD GCELL:CELLID=639, CELLNAME="NR_0702_07021_G1_A", MCC="424", MNC="02", LAC=6112, CI=7021, NCC=6, BCC=0, EXTTP=Normal_cell, IUOTP=Concentric_cell, ENIUO=ON, DBFREQBCCHIUO=Extra, FLEXMAIO=OFF, CSVSP=3, CSDSP=5, PSHPSP=4, PSLPSVP=6, BSPBCCHBLKS=1, BSPAGBLKSRES=4, BSPRACHBLKS=1, TYPE=GSM900_DCS1800,
......................
.............
ADD GTRX:TRXID=0, TRXNAME="M_RAK_JeerExch_G_1879_18791_A-0", FREQ=81, TRXNO=0, CELLID=639, IDTYPE=BYID, ISMAINBCCH=YES, ISTMPTRX=NO, GTRXGROUPID=2556;
ADD GTRX:TRXID=1, TRXNAME="M_RAK_JeerExch_G_1879_18791_A-1", FREQ=24, TRXNO=1, CELLID=639, IDTYPE=BYID, ISMAINBCCH=NO, ISTMPTRX=NO, GTRXGROUPID=2556;
ADD GTRX:TRXID=5, TRXNAME="M_RAK_JeerExch_G_1879_18791_A-2", FREQ=28, TRXNO=2, CELLID=639, IDTYPE=BYID, ISMAINBCCH=NO, ISTMPTRX=NO, GTRXGROUPID=2556;
ADD GTRX:TRXID=6, TRXNAME="M_RAK_JeerExch_G_1879_18791_A-3", FREQ=67, TRXNO=3, CELLID=639, IDTYPE=BYID, ISMAINBCCH=NO, ISTMPTRX=NO, GTRXGROUPID=2556;
Update
I am getting values like shown below
using (StreamReader sr = File.OpenText(filename))
{
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("ADD GCELL:"))
{
var gtrx = new Gtrx
{
CellId = int.Parse(PullValue(s, "CELLID")),
Freq = int.Parse(PullValue(s, "FREQ")),
TrxNo = int.Parse(PullValue(s, "TRXNO")),
IsMainBcch = PullValue(s, "ISMAINBCCH").ToUpper() == "YES",
TrxName = PullValue(s, "TRXNAME"),
};
}
}
UPDATE
I used facade concept, but now it is taking lot of time. I am not sure whether I am using any bad logic two times I am iterating text file one for getting regular values and other for getting concatenated values
private class Gtrx
{
public int Freq { get; set; }
public int TrxNo { get; set; }
public string TrxName { get; set; }
public int CellId { get; set; }
public bool IsMainBcch { get; set; }
}
private class Gcell
{
public int CellId { get; set; }
public string CellName { get; set; }
public string Mcc { get; set; }
public int Lac { get; set; }
public int Ci { get; set; }
}
private class GcellGtrx
{
public Gcell Gcell { get; set; }
public Gtrx Gtrx { get; set; }
}
using (var sr = new StringReader(data))
{
string line = sr.ReadLine();
while (line != null)
{
line = line.Trim();
if (line.StartsWith("ADD GCELL:"))
{
var gcell = new Gcell
{
CellId = int.Parse(PullValue(line, "CELLID")),
CellName = PullValue(line, "CELLNAME"),
Ci = int.Parse(PullValue(line, "CI")),
Lac = int.Parse(PullValue(line, "LAC")),
Mcc = PullValue(line, "MCC")
};
var gcellGtrx = new GcellGtrx();
gcellGtrx.Gcell = gcell;
_dictionary.Add(gcell.CellId, gcellGtrx);
}
if (line.StartsWith("ADD GTRX:"))
{
var gtrx = new Gtrx
{
CellId = int.Parse(PullValue(line, "CELLID")),
Freq = int.Parse(PullValue(line, "FREQ")),
TrxNo = int.Parse(PullValue(line, "TRXNO")),
IsMainBcch = PullValue(line, "ISMAINBCCH").ToUpper() == "YES",
DEFINED_TCH_FRQ = null,
TrxName = PullValue(line, "TRXNAME")
};
if (!intarr.Contains(gtrx.CellId))
{
if (!_dictionary.ContainsKey(gtrx.CellId))
{
// No GCell record for this id. Do something!
continue;
}
intarr.Add(gtrx.CellId);
string results = string.Empty;
var result = String.Join(",",
from ss in File.ReadLines(filename)
where ss.Contains("ADD GTRX:")
where int.Parse(PullValue(ss, "CELLID")) == gtrx.CellId
where PullValue(ss, "ISMAINBCCH").ToUpper() != "YES"
select int.Parse(PullValue(ss, "FREQ")));
results = result;
var gtrxnew = new Gtrx
{
DEFINED_TCH_FRQ = results
};
_dictionary[gtrx.CellId].Gtrx = gtrx;
}
line = sr.ReadLine();
}
}
UPDATE
Finally I did it like first I saved lines starting with ADD GTRX in to an array by using File. Readalllines and then used only that array to get concatenated string instead of storing entire text file and got some performance improvement.
If I convert my Text files that contain hundreds of thousands of lines each into xml and then retrieve data from xml file rather from text file, will it make any performance improvement? If I use datatable and dataset rather than classes here will be a performance improvement?

Create gtrxs collection to store Gtrx objects and read data from file in to gtrxs. Then you can use LINQ (ming need to add using System.Linq;) to find Gtrx objects that are matching your requirements and call Select to get list of Freq values. Once you have a list, you can simply use String.Join(",", freqValues) to build up CSV string.
var gtrxs = new List<Gtrx>();
using (StreamReader sr = File.OpenText(filename))
{
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("ADD GCELL:"))
{
var gtrx = new Gtrx
{
CellId = int.Parse(PullValue(s, "CELLID")),
Freq = int.Parse(PullValue(s, "FREQ")),
TrxNo = int.Parse(PullValue(s, "TRXNO")),
IsMainBcch = PullValue(s, "ISMAINBCCH").ToUpper() == "YES",
TrxName = PullValue(s, "TRXNAME"),
};
gtrxs.Add(gtrx);
}
}
}
IEnumerable<int> freqValues = gtrxs.Where(x => x.CellId == 639 && x.IsMainBcch == false).Select(x => x.Freq);
string result = String.Join(",", freqValues);

Does this work for you?
var result = String.Join(",",
from s in File.ReadAllLines(filename)
where s.Contains("ADD GCELL:")
where int.Parse(PullValue(s, "CELLID")) == 639
where PullValue(s, "ISMAINBCCH").ToUpper() != "YES"
select int.Parse(PullValue(s, "FREQ")));

Related

Convert List<string> to List<object> in C#

I have a list of string that looks something like this:
var rawData = new List<string>(){ "EUR/USD;123" , "EUR/GBP;321", "BTC/USD;2321"};
I have the following structure:
public class Data
{
public string instrument { get; set; }
public string positions { get; set; }
}
My goal is to have a list of the string data, splited on the ';' char and converted to a list of objects.
var processedData = new List<Data>();
// processedData[0] ( instrument = EUR/USD, positions = 123 )
// processedData[1] ( instrument = EUR/GBP, positions = 321)
// processedData[2] ( instrument = BTC/USD, positions = 2321)
Do you have any idea how can I do this ?
You can try Linq and query rawData:
var processedData = rawData
.Select(item => item.Split(';'))
.Select(items => new Data() {
instrument = items[0],
positions = items[1]
})
.ToList();
foreach(var rawString in rawData){
var split = rawString.Split(";");
processedData.Add(new Data(){
instruments = split[0],
positions = split[1]
});
}
You can try this code below
private static void TestFunc()
{
var rawData = new List<string>() { "EUR/USD;123", "EUR/GBP;321", "BTC/USD;2321" };
var processedData = new List<Data1>();
foreach (var item in rawData)
{
var ins = item.Split(";")[0];
var pos = item.Split(";")[1];
processedData.Add(new Data1(ins, pos));
}
}
you can use linq
void Main()
{
var rawData = new List<string>() { "EUR/USD;123", "EUR/GBP;321", "BTC/USD;2321" };
rawData.Select(s =>
new Data() {instrument= s.Split(";")[0],positions = (s.Split(";").Count() > 1) ? s.Split(";")[1] : null})
.ToList().Dump();
}
public class Data
{
public string instrument { get; set; }
public string positions { get; set; }
}

How Can I Create One xml file with Multiple XML douments inside from a text file

I am a C# beginner programmer. I have a text file, which is my source, with multiple rows of data. I want to create one xml file with multiple xml documents inside the file. The xml documents are generated from the rows of data in the text file. I can only get one xml document to generate in the A0x.xml file that is created. My code only reads the first row of data and generates one xml document instead to multiple xml documents. Below are 8 rows from the M24EX.txt file. Please help!!
A0ASMSS3110004624190 EA00008FB239980940001RAIR A30 0120505 18094133644FT
A0ASMSS5340011122822 HD00001FB239981000001RAIR A6C 0120503 18100124741FT
A0ASMSS5365002870093 EA00003FB239981000002RAIR A6C 0120503 18100125431FT
A0ASMS 5365001671717 EA00005FB239981010001REY2550A6C 0120503133 18101075536SF
A0ASMS 5365001671717 EA00011FB239981010002RGE A6C 0120505129 18101105015FT
A0AFLZ 6625013922071 EA00001FB239981070001RGRN D6C 0120505110 18107150014FT
A0AFLZ 6650013204283 EA00003FB239981070002NGRN D6C 0120504777 18107151015FT
A0ASMSS1650009937278 EA00006FB239981080001RAIR A6C 0120505 18108082906FT
And the code:
Public class Program
{
public static void Main(string[] arg)
{
XDocument A0x = new XDocument();
var IdCode = "511";
var CtrlNbr = "0001";
var PurposeCode = "00";
var TypeCode = "A0";
var EntyIdCode = "OB";
var IdCodeQlfr = "10";
var EntyIdCode1 = "FR";
var DocNbr = "TN";
var AssignNbr = "1";
var NSN = "FS";
var DD = "74";
var AgncyQlfrCode = "DF";
var LstQlfrCode = "0";
DateTime saveUtcNow = DateTime.UtcNow;
DateTime saveNow = DateTime.Now;
var field = new ParseTextFile().Parse();
var tagBuilder = new TagBuilder();
var parent = tagBuilder.BuildParent("File");
var subParent = tagBuilder.BuildParent("T_Requisition_511");
var ParentST = tagBuilder.BuildParent("S_Transaction_Set_Header");
var ST01 = tagBuilder.BuildChild("E_Transaction_Set_Identifier_Code", IdCode);
var ST02 = tagBuilder.BuildChild("E_Transaction_Set_Control_Number", CtrlNbr);
var ParentBR = tagBuilder.BuildParent("S_Beginning_Segment_for_Material_Management");
var BR01 = tagBuilder.BuildChild("E_Transaction_Set_Purpose_Code", PurposeCode);
var BR02 = tagBuilder.BuildChild("E_Transaction_Type_Code", TypeCode);
var BR03 = tagBuilder.BuildChild("E_Date", saveUtcNow.ToString("yyyyMMdd"));
var BR09 = tagBuilder.BuildChild("E_Time", saveUtcNow.ToString("hhmmss"));
var ParentN1 = tagBuilder.BuildParent("L_Name");
var ParentS = tagBuilder.BuildParent("S_Name");
var N101 = tagBuilder.BuildChild("E_Entity_Identifier_Code", EntyIdCode);
var N103 = tagBuilder.BuildChild("E_Identification_Code_Qualifier", IdCodeQlfr);
var N104 = tagBuilder.BuildChild("E_Identification_Code", field.SRAN);
var N106 = tagBuilder.BuildChild("E_Entity_Identifier_Code_1", EntyIdCode1);
var ParentLX = tagBuilder.BuildParent("L_Assigned_Number");
var ParentAN = tagBuilder.BuildParent("S_Assigned_Number");
var LX01 = tagBuilder.BuildChild("E_Assigned_Number", AssignNbr);
var ParentN9 = tagBuilder.BuildParent("S_Reference_Identification");
var N901 = tagBuilder.BuildChild("E_Reference_Identification_Qualifier", DocNbr);
var N902 = tagBuilder.BuildChild("E_Reference_Identification", field.DocumentNumber);
var ParentPO1 = tagBuilder.BuildParent("S_Baseline_Item_Data");
var PO102 = tagBuilder.BuildChild("E_Quantity_Ordered", Convert.ToString(field.Quantity));
var PO103 = tagBuilder.BuildChild("E_Unit_or_Basis_for_Measurement_Code", field.UnitofIssue);
var PO106 = tagBuilder.BuildChild("E_Product_Service_ID_Qualifier", NSN);
var PO107 = tagBuilder.BuildChild("E_Product_Service_ID", field.StockNumber);
var ParentSE = tagBuilder.BuildParent("S_Transaction_Set_Trailer");
var SE01 = tagBuilder.BuildChild("E_Number_of_Included_Segments", new CountSegmentTags().CountSgmts().ToString());
var SE02 = tagBuilder.BuildChild("E_Transaction_Set_Control_Number", CtrlNbr);
parent.Add(subParent);
subParent.Add(ParentST);
ParentST.Add(ST01);
ParentST.Add(ST02);
subParent.Add(ParentBR);
ParentBR.Add(BR01);
ParentBR.Add(BR02);
ParentBR.Add(BR03);
ParentBR.Add(BR09);
subParent.Add(ParentN1);
ParentN1.Add(ParentS);
ParentS.Add(N101);
ParentS.Add(N103);
ParentS.Add(N104);
ParentS.Add(N106);
subParent.Add(ParentLX);
ParentLX.Add(ParentAN);
ParentAN.Add(LX01);
ParentLX.Add(ParentN9);
ParentN9.Add(N901);
ParentN9.Add(N902);
ParentLX.Add(ParentPO1);
ParentPO1.Add(PO102);
ParentPO1.Add(PO103);
ParentPO1.Add(PO106);
ParentPO1.Add(PO107);
ParentSE.Add(SE01);
ParentSE.Add(SE02);
A0x.Add(parent);
A0x.Declaration = new XDeclaration("1.0", "utf-8", "true");
A0x.Save("M24EX.xml");
}
public class TagBuilder
{
public XElement BuildParent(string name)
{
return new XElement(name);
}
public XElement BuildChild(string name, string value)
{
var tag = new XElement(name);
tag.Add(value);
return tag;
}
}
public void Read()
{
int counter = 0;
string line;
StreamReader file = new StreamReader("M24EX.txt");
while ((line = file.ReadLine()) != null)
if (line.StartsWith("A0")) // only pull "A0x" records
{
counter++;
Console.WriteLine("{0}:{1}", counter, line);
}
file.Close();
}
public class ParseTextFile
{
public TransactionFields Parse()
{
StreamReader file = new StreamReader("M24Ex.txt");
string line;
int counter = 0;
var field = new TransactionFields();
while ((line = file.ReadLine()) != null)
if (line.StartsWith("A0"))
{
//Assigns field to the Transaction field names
field.DocumentIdentifier = line.Substring(0, 3).Trim(); // Tric
field.RoutingIdentifier = line.Substring(4, 3).Trim();
field.MediaStatusCode = line.Substring(7, 1).Trim();
field.StockNumber = line.Substring(7, 15).Trim();
field.UnitofIssue = line.Substring(22, 2).Trim();
field.Quantity = Convert.ToInt32(line.Substring(24, 5));
field.DocumentNumber = line.Substring(29, 14).Trim();
field.SRAN = line.Substring(29, 6).Trim();
field.DemandCode = line.Substring(44, 1).Trim();
field.SupplementaryAddress = line.Substring(45, 6).Trim();
field.SignalCode = line.Substring(51, 1).Trim();
field.FundCode = line.Substring(52, 2).Trim();
field.DistributionCode = line.Substring(54, 3).Trim();
field.ProjectCode = line.Substring(57, 3).Trim();
field.Priority = line.Substring(60, 2).Trim();
field.ReqDeliveryDate = line.Substring(62, 3).Trim();
field.AdviceCode = line.Substring(65, 2).Trim();
field.DateReceiptofReq = line.Substring(67, 3).Trim();
field.PurposeCode = line.Substring(70, 1).Trim();
field.ConditionCode = line.Substring(71, 1).Trim();
field.MgmtCode = line.Substring(72, 1).Trim();
}
file.Close();
return field;
}
}
public class ConvertXmlToText
{
public void ConvertXmlDoc()
{
string onlyContent = string.Empty;
XmlDocument xdoc = new XmlDocument();
xdoc.Load("A0x.xml");
var file = xdoc.SelectNodes("File/T_Requisition_511");
for (int i = 0; i < file.Count; i++)
{
onlyContent += string.Format("\n", i);
foreach (XmlNode node in file[i].ChildNodes)
onlyContent += string.Format("{0},", node.InnerText);
}
File.WriteAllText("A0x.txt", onlyContent);
}
}
public class TransactionFields
{
public string DocumentIdentifier { get; set; }
public string RoutingIdentifier { get; set; }
public string MediaStatusCode { get; set; }
public string StockNumber { get; set; }
public string UnitofIssue { get; set; }
public int Quantity { get; set; }
public string DocumentNumber { get; set; }
public string SRAN { get; set; }
public string DemandCode { get; set; }
public string SupplementaryAddress { get; set; }
public string SignalCode { get; set; }
public string FundCode { get; set; }
public string DistributionCode { get; set; }
public string ProjectCode { get; set; }
public string Priority { get; set; }
public double UnitPrice { get; set; }
public string Date { get; set; }
public string Time { get; set; }
}

Parsing txt file to List

I have a txt file that want to store into a array. I'm running into a problem parsing when I have additional items on single line, as the pipe(|) would indicate another item to be stored.
Inv # Date term qty description price Tax
3221409:2017/01/12:215|10:WD2002:2TB Hard Drive:121.66:N|20:KG240S:240GB SSD:125.10:N|20:KG120S:120GB SSD:78.75:N
I'm trying to first try to open the file and show each element to the console. getting index outside the bounds of the array. The file doesn't have headers I provided them for information.
//this object lets you read from a file.
StreamReader streamReader = null;
string lineData;
string[] lineElements;
if (File.Exists(path))
{
Console.WriteLine("Woohoo file found");
try
{
int invoice;
String invoicedate;
int term;
int qty;
string description;
Boolean tax;
streamReader = new StreamReader(path);
while (streamReader.Peek() > 0)
{
lineData = streamReader.ReadLine();
var parts = lineData.Split('|');
lineElements = parts.First().Split(':');
invoice = int.Parse(lineElements[0]);
invoicedate = (lineElements[1]);
term = int.Parse(lineElements[2]);
qty = int.Parse(lineElements[3]);
Console.WriteLine(invoice);
Console.WriteLine(invoicedate);
Console.WriteLine(term);
Console.WriteLine(qty);
}
First define a structure that can hold the informations
public class InventoryData
{
public string Inv { get; set; }
public DateTime Date { get; set; }
public string Term { get; set; }
public IList<InventoryArticle> Articles { get; set; }
}
public class InventoryArticle
{
public int Quantity { get; set; }
public string Whatever { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public bool Tax { get; set; }
}
then two methods, that will parse a single line into the structure
static InventoryData ParseInventoryData( string data )
{
var parts = data.Split( '|' );
var headparts = parts.First().Split( ':' );
var result = new InventoryData
{
Inv = headparts[0],
Date = DateTime.ParseExact( headparts[1], "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture ),
Term = headparts[2],
Articles = parts.Skip( 1 ).Select( part => ParseInventoryArticle( part ) ).ToList(),
};
return result;
}
static InventoryArticle ParseInventoryArticle( string data )
{
var parts = data.Split( ':' );
var result = new InventoryArticle
{
Quantity = int.Parse( parts[0] ),
Whatever = parts[1],
Description = parts[2],
Price = decimal.Parse( parts[3], System.Globalization.CultureInfo.InvariantCulture ),
Tax = parts[4] == "Y",
};
return result;
}
and finally how to parse the content of a file
string[] content = {
"Inv # Date term qty description price Tax",
"3221409:2017/01/12:215|10:WD2002:2TB Hard Drive:121.66:N|20:KG240S:240GB SSD:125.10:N|20:KG120S:120GB SSD:78.75:N" };
var data = content
// skip the header row
.Skip( 1 )
// parse the content
.Select( row => ParseInventoryData( row ) )
.ToList();

Select the Object with linq that best fit the Query strings

I have a situation where I am trying to link two different data source together. see the code below:
static void Main(string[] args)
{
string url = System.Net.WebUtility.UrlDecode("yql");
HttpClient cl = new HttpClient();
var response = cl.GetStringAsync(url).Result;
JObject json = JObject.Parse(response);
var ids = from p in json["p"]
from span in p["span"]
where (string)span["content"] == "01/19/2017"
select (string)span["genre"];
}
this is what the JSON looks likeenter code here
please note this JSON is a little different from what you will get from yql as I shorten it removing bits I don't need. this is the
link to the full JSON - https://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20html%20WHERE%20url%3D%22http%3A%2F%2Fthemoviedb.org%2Fsearch%2Fmovie%3Fquery%3Dsplit%22%20%20AND%20xpath%3D'%2F%2Fdiv%5B%40class%3D%22info%22%5D'&format=json&callback=
I want to be able to query the JSON and select the object that best match this:
string year = "2017";
string genre = "Drama, Thriller, Action";
string title = "split"
or
public class Movie{
public string year {get; set;}
public string title {get; set;}
public Genre genre{get; set;}
}
then
List<Movie> _movie = new List<Movie>()
_movie.add(new Movie{year = 2017, title=split, genre[]=Thriller, Drama, Action})
from the query object and the JSON that from yql... the result should be split 01/19/2017
public class Movie
{
public string Year { get; set; }
public string Title { get; set; }
public string[] Genre { get; set; }
}
class Program
{
static void Main(string[] args)
{
string url = System.Net.WebUtility.UrlDecode("https://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20html%20WHERE%20url%3D%22http%3A%2F%2Fthemoviedb.org%2Fsearch%2Fmovie%3Fquery%3Dsplit%22%20%20AND%20xpath%3D%27%2F%2Fdiv%5B%40class%3D%22info%22%5D%27&format=json&callback=");
HttpClient cl = new HttpClient();
var response = cl.GetStringAsync(url).Result;
JObject json = JObject.Parse(response);
var movies = new List<Movie>();
foreach (var pchild in json["query"]["results"]["div"])
{
// title
var title = pchild["p"][0]["a"]["title"];
var titleStr = title != null ? title.Value<string>() : string.Empty;
// year
var releaseDate = pchild["p"][1]["span"][0]["content"];
string releaseYear = string.Empty;
DateTime temp;
if (releaseDate != null
&& DateTime.TryParse(releaseDate.Value<string>(), System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out temp))
{
releaseYear = temp.Year.ToString();
}
// genres
var genre = pchild["p"][1]["span"][1]["content"];
var genreArr = genre != null
? genre.Value<string>()
.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(st => st.Trim())
.ToArray()
: new string[0];
movies.Add(
new Movie
{
Title = titleStr,
Year = releaseYear,
Genre = genreArr
});
}
// searching for the best match
string titleFilter = "Split";
string yearFilter = "2017";
var genreFilter = new string[] { "Drama", "Thriller", "Action" };
var bestMatches = movies
.OrderByDescending(m => m.Title == titleFilter)
.ThenByDescending(m => m.Year == yearFilter)
.ThenByDescending(m => m.Genre.Intersect(genreFilter).Count());
// the best match
var bestMatch = bestMatches.First();
Console.WriteLine(bestMatch.Title);
Console.WriteLine(bestMatch.Year);
Console.WriteLine(string.Join(",", bestMatch.Genre));
// all the movies already ordered
//foreach (var movie in bestMatches)
//{
// Console.WriteLine(movie.Title);
// Console.WriteLine(string.Join(",", movie.Genre));
// Console.WriteLine(movie.Year);
// Console.WriteLine();
//}
Console.ReadLine();
}
Input:
string titleFilter = "Split";
string yearFilter = "2017";
var genreFilter = new string[] { "Drama", "Thriller", "Action" };
Best match:
Split
2017
Drama,Horror,Thriller
Note that you may have several movies with the same matches.
Input:
string titleFilter = "Split";
string yearFilter = "2016";
var genreFilter = new string[] { "Drama", "Thriller", "Action" };
Best matches (you can uncomment the last part of code to see all the movies ordered):
Split
Fantasy,Drama
2016
Split
Drama
2016

C# How do I create an array/matrix that stores the data?

My file looks like this:
hello,1,2,up
goodbye,0,4,down
...
I have WordToFind which will have the first word from my file, but I want it to have both the words 'hello' and 'goodbye'.
Same for X1Coordinate, I want it to have '1' and '0', but as integers.
So how can I modify my code to do that?
I'm a beginner and I tryed to figure it out for over 3 hours and still didn't manage, so I'm sorry if it's a really basic question.
for (int m = 0; m < Words; m++)
{
string LinesInFile = reader.ReadLine();
string[] WordsWithSpecifics = LinesInFile.Split(',');
string WordToFind = WordsWithSpecifics[0];
int X1Coordinate = int.Parse(WordsWithSpecifics[1]);
int Y1Coordinate = int.Parse(WordsWithSpecifics[2]);
string WordDirection = WordsWithSpecifics[3];
Now I get what you need. Below code will do what you require:
var WordToFind = new List<string>();
var X1Coordinate = new List<int>();
var Y1Coordinate = new List<int>();
var WordDirection = new List<string>();
while((LinesInFile = reader.ReadLine()) != null)
{
string[] WordsWithSpecifics = LinesInFile.Split(',');
WordToFind.Add(WordsWithSpecifics[0]);
X1Coordinate.Add(int.Parse(WordsWithSpecifics[1]));
Y1Coordinate.Add(int.Parse(WordsWithSpecifics[2]));
WordDirection.Add(WordsWithSpecifics[3]);
}
But I personally recommend using a class for storing structured data like this:
class MyDataType
{
public string Word { get; set; }
public int X1 { get; set; }
public int Y1 { get; set; }
public string Direction { get; set; }
}
Then use it like this:
var myData = new List<MyDataType>()
while((LinesInFile = reader.ReadLine()) != null)
{
string[] WordsWithSpecifics = LinesInFile.Split(',');
myData.Add(new MyDataType(){
Word = WordsWithSpecifics[0],
X1 = int.Parse(WordsWithSpecifics[1]),
Y1 = int.Parse(WordsWithSpecifics[2]),
Direction = WordsWithSpecifics[3]
};
}

Categories

Resources