Form the String - c#

I need to form the string in for loop.I get the one by one value in "name" variable.Now I need all the value in namevalues variable? the listbox having Pieter,John,Joseph Items.
How can i do this?
for (int i = 0; i < 2; i++)
{
string name = Listboxs.Items[i].ToString();
string namevalues = ??;
}
Expected Output is : Pieter*John*Joseph

Since Listboxs.Items returns ListBox.ObjectCollection which implements IEnumerable interface, you can just use string.Join without for loop like;
string.Join("*", Listboxs.Items.Cast<string>());
should return
Pieter*John*Joseph

Use string.Join with Cast()
var namevalues = string.Join("*", Listboxs.Items.Cast<string>().ToArray());

StringBuilder namevalues = new StringBuilder("");
for(int i =0; i<2; i++)
{
if(namevalues.Length >0 )
{
namevalues.Append("*" + Listboxs.Items[i].ToString());
}
else
{
namevalues.Append(Listboxs.Items[i].ToString());
}
}

Related

split a number into an array of strings

There is a list of candidates.
candid: {12,14,16,19,25,64,78}
Code :
for (int i = 0; i < candid.Count; i++)
{
var searchTerm = candid[i].ToString();
var searchItems = searchTerm.ToCharArray().ToString();
foreach (Tran b in transactions)
{
string[] temp = new string[b.itemsUtilities.Count];
int j = 0;
foreach (ItemUtility c in b.itemsUtilities)
{
temp[j] = c.item.ToString();
j = j + 1;
}
if (searchItems.All(a => temp.Contains(a)))
arraye[i] = arraye[i] + (b.transactionUtility);
}
}
I receive the following error:
'string[]' does not contain a definition for 'Contains' and the best
extension method overload 'Queryable.Contains(IQueryable,
char)' requires a receiver of type 'IQueryable'
If code changed from : var searchItems = searchTerm.ToCharArray().ToString();
To : var searchItems = searchTerm.split();
This error is fixed, But this split command does not separate numbers.
I guess you want to separate the numbers into a string[].
var searchItems = searchTerm.ToCharArray().ToString();
This will always create a single string "System.Char[]" so is not what you want.
I guess you want:
string[] searchItems = searchTerm.Select(c => c.ToString()).ToArray();
This should fix the compiler error because searchItems.All will now project strings and not chars.
More that a simple missing include, I do think that you are over thinking
your code seems to be simplify as :
for (int i = 0; i < candid.Count; i++)
{
var searchTerm = candid[i].ToString();
foreach (Tran b in transactions)
{
var tmp = b.itemsUtilities.Select(x=> x.item.ToString()).ToList();
if( searchTerm.All(a=> tmp.Contains (a)){
arraye[i] = arraye[i] + (b.transactionUtility);
}
}
}
And you can simplify again instead of for each you filter Trasanction based on the if condition.
And if your candid is 11 no need to check twice for 1 so a simple Distinct() will help here.

All permutations of form options

I'm trying to test a form by submitting a combination of all values to see if it breaks. These are ComboBoxes that I have stored in an ExtraField class
public class ExtraField
{
public String Name = ""; //name of form key
public Dictionary<String, String> Options = new Dictionary<String, String>(); //Format: OptionText, Value
}
I have generated a list of these fields
List<ExtraField> efList = new List<ExtraField>();
I was thinking all possible combinations of these fields could be added to a string list that I can parse (I was thinking name=opt|name=opt|name=opt). I've provided an example of what would work below (where ExtraField list Count==3):
List<ExtraField> efList = new List<ExtraField>();
ExtraField f1 = new ExtraField();
f1.Name = "name1";
f1.Options.Add("text", "option1");
f1.Options.Add("text2", "option2");
f1.Options.Add("text3", "option3");
efList.Add(f1);
ExtraField f2 = new ExtraField();
f2.Name = "name2";
f2.Options.Add("text", "option1");
f2.Options.Add("text2", "option2");
f2.Options.Add("text3", "option3");
f2.Options.Add("text4", "option4");
efList.Add(f2);
ExtraField f3 = new ExtraField();
f3.Name = "name3";
f3.Options.Add("text2", "option1");
f3.Options.Add("text3", "option2");
f3.Options.Add("text4", "option3");
f3.Options.Add("text5", "option4");
f3.Options.Add("text6", "option5");
efList.Add(f3);
Should produce
name1=option1|name2=option1|name3=option1
name1=option1|name2=option1|name3=option2
name1=option1|name2=option1|name3=option3
name1=option1|name2=option1|name3=option4
name1=option1|name2=option1|name3=option5
name1=option1|name2=option2|name3=option1
name1=option1|name2=option2|name3=option2
name1=option1|name2=option2|name3=option3
name1=option1|name2=option2|name3=option4
name1=option1|name2=option2|name3=option5
name1=option1|name2=option3|name3=option1
name1=option1|name2=option3|name3=option2
name1=option1|name2=option3|name3=option3
name1=option1|name2=option3|name3=option4
name1=option1|name2=option3|name3=option5
name1=option1|name2=option4|name3=option1
name1=option1|name2=option4|name3=option2
name1=option1|name2=option4|name3=option3
name1=option1|name2=option4|name3=option4
name1=option1|name2=option4|name3=option5
name1=option2|name2=option1|name3=option1
...etc
All ExtraFields in the list need to have a value and I need all permutations in one format or another. It's a big list with a lot of permutations otherwise I'd do it by hand.
Well I did it... But I'm not proud of it. I'm sure there is a better way of doing it recursively. Hopefully this helps someone.
public List<String> GetFormPermutations(List<ExtraField> inList)
{
List<String> retList = new List<String>();
int[] listIndexes = new int[inList.Count];
for (int i = 0; i < listIndexes.Length; i++)
listIndexes[i] = 0;
while (listIndexes[inList.Count-1] < inList.ElementAt(inList.Count-1).Options.Count)
{
String cString = "";
//after this loop is complete. a line is done.
for (int i = 0; i < inList.Count; i++) {
String key = inList.ElementAt(i).Name;
Dictionary<String, String> cOptions = inList.ElementAt(i).Options;
String value = cOptions.ElementAt(listIndexes[i]).Value;
cString += key + "=" + value;
if (i < inList.Count - 1)
cString += "|";
}
retList.Add(cString);
listIndexes[0]++;
for(int i = 0; i < inList.Count -1; i++)
{
if (listIndexes[i] >= inList.ElementAt(i).Options.Count)
{
listIndexes[i] = 0;
listIndexes[i + 1]++;
}
}
}
return retList;
}
UPDATED ANSWER
So I managed to do it recursively. I haven't done this since college :D
Here's the whole class:
https://gist.github.com/Rastamas/8070ae7e1471d2183451a17bcf061376
PREVIOUS ANSWER BELOW
This goes through your list and adds the strings to a StringBuilder in the format you showed
foreach (var item in efList)
{
foreach (var option in item.Options)
{
stringBuilder.Append(String.Format("{0}={1}|", item.Name, option.Value));
}
stringBuilder.Remove(stringBuilder.Length - 1, 1);
stringBuilder.AppendLine();
}
Then you can just use stringBuilder.ToString() to get the whole list.

IComparer for string that checks if x starts with y

I've got an array of strings and I need to get all strings, that start with some 'prefix'. I wanna use Array.BinarySearch(). Is it possible? And how should I write a comparer if so?
No, you cannot use BinarySearch in this case. You could use Enumerable.Where instead:
Dim query = From str In array Where str.StartsWith("prefix")
or with (ugly in VB.NET) method synatx:
query = array.Where(Function(str) str.StartsWith("prefix"))
Edit: whoops, C#
var query = array.Where(s => s.StartsWith("prefix"));
Use ToArray if you want to create a new filtered array.
It's easy to create your own StartsWithComparer:
class StartsWithComparer : IComparer<string>
{
public int Compare(string a, string b) {
if(a.StartsWith(b)) {
return 0;
}
return a.CompareTo(b);
}
}
As others pointed out, this will only return one index. You can have a couple of helpers to return all items:
IEnumerable<string> GetBefore(IList<string> sorted, int foundIndex, string prefix) {
for(var i = foundIndex - 1; i >= 0; i--) {
if(sorted[i].StartsWith(prefix)) {
yield return sorted[i];
}
}
}
IEnumerable<string> GetCurrentAndAfter(IList<string> sorted, int foundIndex, string prefix) {
for(var i = foundIndex; i < sorted.Count; i++) {
if(sorted[i].StartsWith(prefix)) {
yield return sorted[i];
}
}
}
Then to use it:
var index = sorted.BinarySearch("asdf", new StartsWithComparer());
var previous = GetBefore(sorted, index, "asdf");
var currentAndAfter = GetCurrentAndAfter(sorted, index, "asdf");
You can wrap the whole thing in your own class, with a single method that returns all items that start with your prefix.

Foreach loop for three List<string>

I want to loop through three List<string>. I'm sending ajax request containing 3 parameter as Array.
This is my WebMethod.
public string saveEachTask(string imageData, string desc, string tid)
{
var imglist = imageData.Split(',').ToList();
var desclist = desc.Split(',').ToList();
var idlist = tid.Split(',').ToList();
// here i want a foreach loop for above three list
return "Saved Succesfully";
}
Edit: in loop how can I identity which string is for img, desc and id
Any Help appreciated.
Perhaps something like this:
foreach (var list in new[] {imglist, desclist, idlist})
{
foreach (var s in list)
{
}
}
Use one loop and each iteration process each list.
public string saveEachTask(string imageData, string desc, string tid)
{
var imglist = imageData.Split(',').ToList();
var desclist = desc.Split(',').ToList();
var idlist = tid.Split(',').ToList();
int maxLength = Math.Max(imglist.Count, Math.Max(desclist.Count, idlist.Count));
for (int i = 0; i < maxLength; ++i)
{
string imgItem = (i < imglist.Count ? imglist[i] : null);
string descItem = (i < desclist.Count ? desclist[i] : null);
string idItem = (i < idlist.Count ? idlist[i] : null);
// TODO: Process imgItem, descItem, idItem
}
return "Saved Succesfully";
}
If you need to handle everything the same way in your loop, you could try:
foreach(var s in imglist.Union(desclist.Union(idlist)))
{
// do something with the string
}

Foreach loop to check the empty string and assign it a value c#

I dont much idea about Foreach Loop
I have 4 String Variables and i am storing the encrypted values from app.config in those varialbles.My Work is to Detect if there is data in those 4 variables.Even if one doesnt have values i want to pass a default encrypted values to it.I started doing like this......
string EncValue = oEncrypt.EncryptBase64String("NO Data Found");
UpdateOrCreateAppSetting("UserName", ref MPScmUserName);
UpdateOrCreateAppSetting("Password", ref MPScmPassword);
UpdateOrCreateAppSetting("DBUserName", ref MPDbUserName);
UpdateOrCreateAppSetting("DBPassword", ref MPDbPassword);
var list5 = from docs in doc1.Descendants("appender").Elements()
where docs.Name == "file"
select docs;
var element5 = list5.FirstOrDefault();
MPLoadAppConfig = appConfigFile1;
MPErrorLog = element5.Attribute("value").Value;
string[] namesArray = new string[] {
MPScmUserName,MPScmPassword,MPDbUserName,MPDbPassword};
foreach (string i in namesArray)
{
if (i is string)
{
if (i == "")
{
i = EncValue.ToString();
}
}
}
How should i assign default encrypted value to the strings in that array which is a empty string. Please Help me....
You don't need to say if (i is string) because it's already a string.
In another if block you may say
if(string.IsNullOrEmpty(i))
{
}
or you may use:
string[] arr = new string[] { "","A"};
for (int i = 0; i < arr.Length; i++)
{
if (string.IsNullOrEmpty(arr[i]))
{
arr[i] = "Hello";
}
}
Looping on the string array and changing the value of current string doesn't means you are changing the value of the string inside the array. When foreach loops on your array it returns a new string instance in i, so changing that i don't change the value in namesArray.
You need a traditional for loop with an indexer to access directly to the namesArray
for(int i = 0; i < namesArray.Length; i++)
{
if (namesArray[i] == string.Empty)
{
namesArray[i] = EncValue.ToString();
}
}
No need for the if (i is string) part because you already know it's a string. You should probably also use string.IsNullOrWhiteSpace(); to test for an empty string.
Edit (shameless copy from Mark's answer):
for (int i = 0; i < namesArray.Length; ++i)
{
if (string.IsNullOrWhiteSpace(namesArray[i]))
{
namesArray[i] = EncValue.ToString();
}
}
You can't modify the variable in a foreach loop. Your code should give you the following compile error:
Cannot assign to 'i' because it is a 'foreach iteration variable'
You could do this using LINQ:
namesArray = namesArray.Select(s => s == "" ? EncValue.ToString() : s).ToArray();
Alternatively you could use a simple for loop:
for (int i = 0; i < namesArray.Length; ++i)
{
if (namesArray[i] == "")
{
namesArray[i] = EncValue.ToString();
}
}
string[] newNamesArray =
Enumerable.Select(namesArray, s => s == "" ? EncValue : s).ToArray();

Categories