I have this string
Dispatching System,proposal,to be
sent,main,2022-006,related,2022-017,related
that is composed of this c# code
List<string> value1 = new List<string>();
foreach (string item in Request.Form)
{
if (item.Contains("ddl"))
{
value1.Add(Request.Form[item]);
}
}
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('value1:\\n" +
string.Join(",", value1) + "');", true);
Using the code above the output is
Dispatching System,proposal,to be
sent,main,2022-006,related,2022-017,related
Now I need to extract from this string from element number 5 to all subsequent elements, that is
2022-006,related,2022-007,related
and storing a row for each string value in a database table, that is
t
q
2022-006
related
2022-017
related
Expected output
2022-006
related
2022-017
related
But the expected ouput now is empty...
This is my c# code
List<string> value1 = new List<string>();
foreach (string item in Request.Form)
{
if (item.Contains("ddl"))
{
value1.Add(Request.Form[item]);
List<string> value2 = item.Split(',').ToList();
for (int i = 4; i < value2.Count; i++)
{
//Insert into db
Response.Write(value2[i] + "<br />" + value2[i + 1] + "<br /><br />");
i++;
}
}
}
Thanks in advance for any help, really appreciated.
Solution
List<string> value1 = new List<string>();
foreach (string item in Request.Form)
{
if (item.Contains("ddl"))
{
value1.Add(Request.Form[item]);
}
}
var requestDLL = string.Join(",", value1);
var value2 = requestDLL.Split(',');
for (int i = 4; i < value2.Length; i++)
{
//Insert into db
Response.Write(value2[i] + "<br />" + value2[i + 1] + "<br /><br />");
i++;
}
Output
2022-006
related
2022-017
related
Here you can find the code that return the expected output https://dotnetfiddle.net/8aBrZj
using System;
public class Program
{
public static void Main()
{
var requestDLL = "Dispatching System,proposal,to be sent,main,2022-006,related,2022-017,related";
var value2 = requestDLL.Split(',');
for (int i = 4; i < value2.Length; i++)
{
//Insert into db
Console.Write(value2[i] + "\n" + value2[i + 1] + "\n \n");
i++;
}
}
}
Related
I have working example without the conditional here.
public string RenderPostTags(DMCResultSet resultSet)
{
string output = "";
string filterForm = RenderFilterForm(resultSet);
string pagination = RenderPagination(resultSet);
List<XElement> items = resultSet.items;
foreach(XElement i in items)
{
string tags = "";
if (i.Element("tags") != null)
{
foreach(string tag in i.Element("tags").Elements("tag"))
{
tags += "" + tag + "";
}
}
output += tags;
}
return output;
}
I know just putting a count on it wont work but I've tried several different methods and they haven't worked for me. Could be a syntactical error I'm a total C# noob.
But I need to output adjusted html using a if else conditional similar to this
public string RenderPostTags(DMCResultSet resultSet){
string output = "";
string filterForm = RenderFilterForm(resultSet);
string pagination = RenderPagination(resultSet);
List<XElement> items = resultSet.items;
foreach(XElement i in items){
string tags = "";
if (i.Element("tags") != null) {
int count = 1;
int total = i.Element("tags").Elements("tag").Count;
foreach(string tag in i.Element("tags").Elements("tag")) {
if(count == total){
tags += "" + tag + "";
count++;
}else{
tags += "" + tag +","+ " " + "";
count++;
}
}
}
output += tags;
}
return output;
}
Methods I have tried can be found on this thread.
Foreach loop, determine which is the last iteration of the loop
Thank you for any assitance.
As #Sach said, use the for loop instead of foreach.
string output = "";
List<XElement> items = new List<XElement>();
foreach (XElement i in items)
{
string tags = "";
if (i.Element("tags") != null && i.Element("tags")?.Elements("tag") != null)
{
List<XElement> tagItems = i.Element("tags").Elements("tag").ToList();
if (tagItems == null) continue;
for (int j = 0; j < tagItems.Count(); j++)
{
XElement tag = tagItems[j];
if (j == i.Element("tags")?.Elements("tag").Count() - 1)
{
tags += "" + tag + "";
}
else
{
tags += "" + tag + "," + " " + "";
}
}
}
output += tags;
}
You can write your foreach loop like this to capture both conditions. You can use condition ? true : false to write either/or based on the last item in the collection.
int counter = 1; // Start with 1 since we are using != later on.
int totalRecords = i.Element("tags").Elements("tag").Count();
foreach (string tag in i.Element("tags").Elements("tag"))
tags += "" + tag + counter++ != totalRecords ? ", " : string.Empty + "";
Above is equivalent to
if (i.Element("tags") != null)
{
int counter = 1;
int totalRecords = i.Element("tags").Elements("tag").Count();
foreach (string tag in i.Element("tags").Elements("tag"))
{
if (counter++ == totalRecords)
{
tags += "" + tag + "";
}
else
{
tags += "" + tag + ", " + "";
}
}
}
Make a note that IEnumerable does not have a Count property but have a method Count().
So maybe for namespace reasons the count method would not solve my issue.
However after some toil this solution worked perfectly. Thankyou for those to helped me get to this solution.
public string RenderPostTags(DMCResultSet resultSet){
string output = "";
string filterForm = RenderFilterForm(resultSet);
string pagination = RenderPagination(resultSet);
List<XElement> items = resultSet.items;
foreach(XElement i in items){
string tags = "";
if (i.Element("tags") != null) {
foreach(string tag in i.Element("tags").Elements("tag")){
if(tags != "") tags += ", ";
tags += "" + tag +"";
}
}
output += tags;
}
return output;
}
I have a function that retrieves multiple lines of data and I want to display them in a label. My function is as shown below.
public static string GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
}
return res;
}
So far I can only return a string which is the last line of the retrieved data. How can I retrieve all the records? I tries arraylist, but it seems that the AWS web application doesn't allow me to use arraylist. Can anyone please help me to solve this??
Return it as as a Enumberable,
List<String> Results ;
Your method would be
public static List<String> GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
List<String> Results = null;
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
Results = new List<String>();
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
Results.Add(res);
}
return Results;
}
when i export string values which contains decimal numbers like 6,7014
while exporting to csv file it is converting into strange value 67,014
which is inappropriate
function i used is given below:
public void DownloadtoCSV(DataSet ds, String name)
{
string deLimiter = ";";
if (System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencySymbol == "$")
{
deLimiter = ",";
}
StringBuilder sb = new StringBuilder();
sb.Append("sep=" + deLimiter + "\r\n");
foreach (DataTable dataTable in ds.Tables)
{
if (dataTable.Columns.Count != 0)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
if (i == 0)
{
sb.Append(dataTable.Rows[0][i].ToString().Replace(",", " ").Replace("\r\n", " "));
}
else
{
sb.Append(deLimiter + dataTable.Rows[0][i].ToString().Replace(",", " ").Replace("\r\n", " "));
}
}
sb.Append("\r\n");
Int64 k = 0;
if (dataTable.Rows.Count > 0)
{
foreach (DataRow row in dataTable.Rows)
{
if (k != 0)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
if (i == 0)
{
sb.Append("\"" + row[dataTable.Columns[i].ColumnName].ToString().Replace("\"", "\"\"").Replace("\r\n", " ") + "\"");
}
else
{
sb.Append(deLimiter + "\"" + row[dataTable.Columns[i].ColumnName].ToString().Replace("\"", "\"\"").Replace("\r\n", " ") + "\"");
}
}
sb.Append("\r\n");
}
k++;
}
}
}
sb.Append(Environment.NewLine);
}
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Response.ContentType = "Application/save";
Response.AddHeader("content-disposition", "attachment;filename=" + name + ".csv");
Response.ContentEncoding = Encoding.Default;
Response.Write(sb.ToString());
Response.End();
}`enter code here`
Hello I am trying to make a C# program that downloads files but I am having trouble with the array.
I have it split up the text for downloading and put it into a 2 level jagged array (string[][]).
Now I split up the rows up text by the | char so each line will be formatted like so:
{filename}|{filedescription}|{filehttppath}|{previewimagepath}|{length}|{source}
when I use short test text to put it into a text box it displays fine in the text box.
IE: a string like test|test|test|test|test|test
but if I put in a real string that I would actually be using for the program to DL files the only way I get the string to display is to iterate through it with a for or foreach loop. If I try to access the data with the index I get an index missing error. (IE array[0])
So this is the code that gets the array to display:
public Form2(string[][] textList, string path)
{
InitializeComponent();
textBox1.Text = textBox1.Text + path + Environment.NewLine;
WebClient downloader = new WebClient();
foreach (string[] i in textList)
{
for(int j=0;j<i.Length;j++)
{
textBox1.Text = textBox1.Text + i[j] + Environment.NewLine + #"\\newline" + Environment.NewLine;
}
}
}
And then this is the code that gives an index missing error:
public Form2(string[][] textList, string path)
{
InitializeComponent();
textBox1.Text = textBox1.Text + path + Environment.NewLine;
WebClient downloader = new WebClient();
foreach (string[] i in textList)
{
textBox1.Text = textBox1.Text + i[0] + Environment.NewLine;
textBox1.Text = textBox1.Text + i[1] + Environment.NewLine;
textBox1.Text = textBox1.Text + i[2] + Environment.NewLine;
textBox1.Text = textBox1.Text + i[3] + Environment.NewLine;
textBox1.Text = textBox1.Text + i[4] + Environment.NewLine;
textBox1.Text = textBox1.Text + i[5] + Environment.NewLine;
}
}
Any help is this is apreciated I don't see why I can access they data through a for loop but not directly it just doesn't make any sense to me.
Also, here is the code that generates the array:
public String[][] finalList(string[] FileList)
{
String[][] FinalArray = new String[FileList.Length][];
for (int i = 0; i<FinalArray.Length;i++)
{
string[] fileStuff = FileList[i].Split(new char[] {'|'});
FinalArray[i] = fileStuff;
}
return FinalArray;
}
In your first example you are using the actual length of each inner array to do the concatenation. In your second example you are hard coded to the same length yet you said in the intro it was a jagged array.
Can you show what your input text looks like?
you are not doing the same concatenation in first and second example so the resulting stings are very different.
first = "\r\n Crazy Video\r\n\\\\newline\r\nThis Video is absolutly crazy!\r\n\\\\newline\r\nhtt://fakeurl.fake/vidfolder/video.flv\r\n\\\\newline\r\nhtt://fakeurl.fake/imgfolder/img.jpg\r\n\\\\newline\r\n300\r\n\\\\newline\r\nhtt://fakeurl.fake \r\n\\\\newline\r\n"
second = "\r\n Crazy Video\r\nThis Video is absolutly crazy!\r\nhtt://fakeurl.fake/vidfolder/video.flv\r\nhtt://fakeurl.fake/imgfolder/img.jpg\r\n300\r\nhtt://fakeurl.fake \r\n"
using System;
using NUnit.Framework;
namespace ClassLibrary5
{
public class Class1
{
[Test]
public void test()
{
var temp = new[]
{
" Crazy Video|This Video is absolutly crazy!|htt://fakeurl.fake/vidfolder/video.flv|htt://fakeurl.fake/imgfolder/img.jpg|300|htt://fakeurl.fake "
};
var final = finalList(temp);
var first = Form1(final, "path");
var second = Form2(final, "path");
Assert.IsTrue(first.CompareTo(second) == 0);
}
public string Form1(string[][] textList, string path)
{
string textString = path + Environment.NewLine;
foreach (string[] i in textList)
{
for (int j = 0; j < i.Length; j++)
{
textString = textString + i[j] + Environment.NewLine + #"\\newline" + Environment.NewLine;
}
}
return textString;
}
public string Form2(string[][] textList, string path)
{
string textString = path + Environment.NewLine;
foreach (string[] i in textList)
{
textString = textString + i[0] + Environment.NewLine;
textString = textString + i[1] + Environment.NewLine;
textString = textString + i[2] + Environment.NewLine;
textString = textString + i[3] + Environment.NewLine;
textString = textString + i[4] + Environment.NewLine;
textString = textString + i[5] + Environment.NewLine;
}
return textString;
}
public String[][] finalList(string[] FileList)
{
String[][] FinalArray = new String[FileList.Length][];
for (int i = 0; i < FinalArray.Length; i++)
{
string[] fileStuff = FileList[i].Split(new char[] {'|'});
FinalArray[i] = fileStuff;
}
return FinalArray;
}
}
}
Are you sure each String[] in string[][] textList has 6 elements?
Try to replace:
for(int j=0;j<i.Length;j++)
{
textBox1.Text = textBox1.Text + i[j] + Environment.NewLine + #"\\newline" + Environment.NewLine;
}
with:
for(int j=0;j<6;j++)
{
textBox1.Text = textBox1.Text + i[j] + Environment.NewLine + #"\\newline" + Environment.NewLine;
}
And see if you get the same result. Your middle one has different logic than your first one. To troubleshoot, first make the logic the same, and then continue troubleshooting from there.
I have this code:
List<string> lineList = new List<string>();
foreach (var line in theFinalList)
{
if (line.PartDescription != "")
lineList.Add(line.PartDescription + " " + line.PartNumber + "\n");
else
lineList.Add("N/A " + line.PartNumber + "\n");
//
//This is what I am trying to fix:
if (lineList.Contains("FID") || lineList.Contains("EXCLUDE"))
// REMOVE THE item in the lineList
}
I am trying to go through theFinalList in a foreach loop and add each line to a new list called lineList.
Once added, I want to remove any entries from that list that contain the text "FID" or "EXCLUDE".
I am having trouble removing the entry, can someone help me?
why add them when you want to remove them right after:
lineList = theFinalList.Select( line =>
{
if (line.PartDescription != "")
return line.PartDescription + " " + line.PartNumber + "\n";
else
return "N/A " + line.PartNumber + "\n";
})
.Where(x => !(x.Contains("FID") || x.Contains("EXCLUDE")))
.ToList();
The following code sample iterates through the lineList and removes lines that contain FID or EXCLUDE.
for(int i = lineList.Count - 1; i >= 0; i--)
{
if (lineList[i].Contains("FID") || lineList[i].Contains("EXCLUDE"))
lineList.RemoveAt(i);
}
It is important to traverse a list in reverse order when deleting items.
You can't remove the items in your theFinalList list while you are iterating over theFinalList in a foreach loop. In this case, you may get System.InvalidOperationException with the message “Collection was modified; enumeration operation may not execute.”
you have to do something like this:
List<string> removals = new List<string>();
foreach (string s in theFinalList)
{
//do stuff with (s);
removals.Add(s);
}
foreach (string s in removals)
{
theFinalList.Remove(s);
}
try
foreach (var line in theFinalList)
{
string T = "";
if (line.PartDescription != "")
T = line.PartDescription + " " + line.PartNumber + "\n";
else
T = "N/A " + line.PartNumber + "\n";
if (!(T.Contains("FID") || T.Contains("EXCLUDE"))
lineList.Add (T);
}
I think its more logical approach
Regex exclude = new Regex("FID|EXCLUDE");
foreach (var line in theFinalList.Where(
ln => !exclude.Match(ln.PartDescription).Success &&
!exclude.Match(ln.PartNumber ).Success))){
string partDescription = "N/A";
if(!string.IsNullOrWhiteSpace(line.PartDescription)){
partDescription = line.PartDescription;
}
lineList.Add(partDescription + " " + line.PartNumber + "\n");
}
edit regex for your needs (ignore case maybe or multiline, probably compiled too) and feel free to replace "\n" with Environment.NewLine
Try this:
var excludingTexts = new [] { "FID", "EXCLUDE" }
lineList = lineList.Where(y => !excludingTexts.Any(x => line.PartDescription.Contains(x) || line.PartNumber.Contains(x))).ToList();
Or you can rewrite it as:
var excludingTexts = new [] { "FID", "EXCLUDE" }
List<string> lineList = (from line in theFinalList
where !excludingTexts.Any(x => line.PartDescription.Contains(x) || line.PartNumber.Contains(x))
select line.PartDescription != "" ?
line.PartDescription + " " + line.PartNumber + "\n" :
"N/A " + line.PartNumber + "\n"
).ToList();