comma delimited string collection - asp.net-mvc-3

CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();
string itemList = Convert.ToString(HIGList[i].AccountId) + '$' + "HIG" + ',' + '$';
commaStr.Add(itemList);
HigList = HigList + commaStr;
When i am trying to execute this it is showing error like
Value may not contain ','

CommaDelimitedStringCollection is intended to generate a comma delimited string. it means that you add values to it and when you call it's ToString() method, you get the values separated with a comma between each value.
That's why it won't let you add a value with a (non-escaped) comma , in it, as it violates it's very use.
For example:
var csv = new CommaDelimitedStringCollection();
var cities = new[] { "New York", "Log Angeles", "Toronto", "San Francisco" };
foreach (var city in cities)
{
csv.Add(city);
}
Console.WriteLine(csv.ToString()); // will output: New York,Log Angeles,Toronto,San Francisco
And in your case:
CommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();
string itemList = Convert.ToString(HIGList[i].AccountId) + '$' + "HIG" + ',' + '$';
commaStr.AddRange(itemList.Split(','));
HigList = HigList + commaStr;

The error message tells you exactly what the problem is and it is immediately visible from the code... You're trying to add a string that contains a comma to a comma delimited string collection. Obviously this makes no sense so an exception is thrown.

Related

replace list value without looping

IList<Item> items = new List<Item>();
items.Add(new Item
{
tag = "{" + Ann + "}",
value = "Anny"
});
items.Add(new Item
{
tag = "{" + John + "}",
value = "Johnny"
});
How can I use Linq to select tag with {John} and replace value with "Jane"?
LINQ is, as the name suggests, more of a query tools. So you can get specific item(s) that you want to modify from a collection using LINQ, but the modification itself is out-of-scope for LINQ.
Assuming that there is always maximum one match to your criteria, you can do as follows :
var john = items.FirstOrDefault(o => o.tag == "{John}");
if(john != null)
{
john.value = "Jane";
}
Otherwise, you can use LINQ Where(o => o.tag == "{John}") to get the target items for modification. But then you'll need to iterate through the result to actually update the value of each matched item.
items.Where(o => o.tag == "{"+John+"}").ToList().ForEach(item =>{
item.value = "Jane";
});
Here is working fiddle

JDBC ResultSet get column from different tables

i wan to retrieve data from query involving many tables.
i have a query as follows
String sql = "SELECT "
+ "s.Food_ID AS 'Sales_FoodID', "
+ "f.Food_Name AS 'foodName' "
+ "FROM Ordering o, Sales s, Food f"
+ " WHERE o.Table_No = " + tableNo + ""
+ " AND o.Paid = '" + NOT_PAID + "'"
+ " AND s.Order_ID = o.Order_ID"
+ " AND f.Food_ID = s.Food_ID;";
resultSet = statement.executeQuery(sql);
no error were found when i run the program, but after i add this line to get a table's column data:
String orderID = resultSet.getString("foodName");
i'm given this error:
java.sql.SQLException: Column not found
anyone know why?
You have to use next() method.
You should know that ResultSet is implicitly positioned on position before first row so you need to call next to get current position and if is valid, it returns true, else returns false (cursor is positioned after the last row).
rs = statement.executeQuery(sql);
while (rs.next()) {
String orderID = rs.getString(2);
}
Note: You can use also rs.getString(<columnName>) but in case when you know how your statement looks i recommend to you use index instead of columnName.
After calling the resultSet.executeQuery() you need to call the next() to pulling the records from db
after that you can call setXxx() provided by Java API

How to insert a new line into database and read value onto my webgrid in razor MVC 3

I am using Razor, MVC3 with Poco entities.
While inserting into the database I am using Enviroment.NewLine as a seperator between two texts.
oldValues += " Name = '" + oldName.Name + "'" + Environment.NewLine ;
oldValues += " Age = '" + oldName.Age + "'" + Environment.NewLine ;
I am then assigning this oldValues string object to one of my columns in the database.
But when I am reading this value onto my webgrid, the formatting does not appear as expected.
What could be the problem here ?
Please suggest me some methods, I have also tried appending
<br />
tags too.
Expected Output in one of my webgrid column:
Old Values are
Name = Yasser
Age = 24
and New Values are
Name = Yasser R
Age =25
Actual Output in one of my webgrid column:
Old Values are Name = Yasser Age = 24 and New Values are Name = Yasser R Age =25
That's the behavior of HTML. You can wrap your text with <pre>Your String Here</pre> and it should display the text as you're expecting it.
With some help from Paul, I have managed to solve this problem
here is what I am using now
logGrid.Column(header: "Message", columnName: "Message", format: #<pre>#item.Message </pre>),

Need an algorithm to group several parameters of a person under the persons name

I have a bunch of names in alphabetical order with multiple instances of the same name all in alphabetical order so that the names are all grouped together. Beside each name, after a coma, I have a role that has been assigned to them, one name-role pair per line, something like whats shown below
name1,role1
name1,role2
name1,role3
name1,role8
name2,role8
name2,role2
name2,role4
name3,role1
name4,role5
name4,role1
...
..
.
I am looking for an algorithm to take the above .csv file as input create an output .csv file in the following format
name1,role1,role2,role3,role8
name2,role8,role2,role4
name3,role1
name4,role5,role1
...
..
.
So basically I want each name to appear only once and then the roles to be printed in csv format next to the names for all names and roles in the input file.
The algorithm should be language independent. I would appreciate it if it does NOT use OOP principles :-) I am a newbie.
Obviously has some formatting bugs but this will get you started.
var lastName = "";
do{
var name = readName();
var role = readRole();
if(lastName!=name){
print("\n"+name+",");
lastName = name;
}
print(role+",");
}while(reader.isReady());
This is easy to do if your language has associative arrays: arrays that can be indexed by anything (such as a string) rather than just numbers. Some languages call them "hashes," "maps," or "dictionaries."
On the other hand, if you can guarantee that the names are grouped together as in your sample data, Stefan's solution works quite well.
It's kind of a pity you said it had to be language-agnostic because Python is rather well-qualified for this:
import itertools
def split(s):
return s.strip().split(',', 1)
with open(filename, 'r') as f:
for name, lines in itertools.groupby(f, lambda s: split(s)[0])
print name + ',' + ','.join(split(s)[1] for s in lines)
Basically the groupby call takes all consecutive lines with the same name and groups them together.
Now that I think about it, though, Stefan's answer is probably more efficient.
Here is a solution in Java:
Scanner sc = new Scanner (new File(fileName));
Map<String, List<String>> nameRoles = new HashMap<String, List<String>> ();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String args[] = line.split (",");
if (nameRoles.containsKey(args[0]) {
nameRoles.get(args[0]).add(args[1]);
} else {
List<String> roles = new ArrayList<String>();
roles.add(args[1]);
nameRoles.put(args[0], roles);
}
}
// then print it out
for (String name : nameRoles.keySet()) {
List<String> roles = nameRoles.get(name);
System.out.print(name + ",");
for (String role : roles) {
System.out.print(role + ",");
}
System.out.println();
}
With this approach, you can work with an random input like:
name1,role1
name3,role1
name2,role8
name1,role2
name2,role2
name4,role5
name4,role1
Here it is in C# using nothing fancy. It should be self-explanatory:
static void Main(string[] args)
{
using (StreamReader file = new StreamReader("input.txt"))
{
string prevName = "";
while (!file.EndOfStream)
{
string line = file.ReadLine(); // read a line
string[] tokens = line.Split(','); // split the name and the parameter
string name = tokens[0]; // this is the name
string param = tokens[1]; // this is the parameter
if (name == prevName) // if the name is the same as the previous name we read, we add the current param to that name. This works right because the names are sorted.
{
Console.Write(param + " ");
}
else // otherwise, we are definitely done with the previous name, and have printed all of its parameters (due to the sorting).
{
if (prevName != "") // make sure we don't print an extra newline the first time around
{
Console.WriteLine();
}
Console.Write(name + ": " + param + " "); // write the name followed by the first parameter. The output format can easily be tweaked to print commas.
prevName = name; // store the new name as the previous name.
}
}
}
}

How to write a let clause using the dot notation style

Using the query expression style, the let clause can be easily written. My question is how to use the dot notation style to write a let clause.
Essentially it's a Select (in most cases) which introduces a transparent identifier - via an anonymous type which encapsulates all the currently specified range variables. For example, this query:
string[] names = { "Jon", "Mark" };
var query = from name in names
let length = name.Length
where length > 3
select name + ": " + length;
is translated into something like this:
var query = names.Select(name => new { name, length = name.Length })
.Where(z => z.length > 3)
.Select(z => z.name + ": " z.length);

Resources