If all three textboxes are empty don't do anything. However below code shows all three are empty too. But I don't want this.
var textBoxes = new [] {
new { txb = txtUserName, name = "txtUserName" },
new { txb = txtPassw, name = "txtPassw" },
new { txb = txtDatabase , name = "txtDatabase " }
};
var empty = textBoxes.Where(x => x.txb.Text == "").ToList();
if(empty.Any())
{
MessageBox.Show("Please enter " + String.Join(" and ", empty.Select(x => x.name)));
}
A modification of #MarcinJuraszek's answer:
var textBoxes = new [] {
new { txb = txtUserName, name = "txtUserName" },
new { txb = txtPassw, name = "txtPassw" },
new { txb = txtDatabase , name = "txtDatabase " }
};
var empty = textBoxes.Where(x => String.IsWhitespaceOrEmpty(x.txb.Text)).ToList();
if(empty.Any() && empty.Count != textboxes.Length)
{
MessageBox.Show("Please enter " + String.Join(" and ", empty.Select(x => x.name)));
}
I added an additional check to not display the message box if ALL the strings are empty. I also changed the comparison to use IsWhitespaceOrEmpty in case you have a bunch of spaces (which is generally not valid input). You could also use IsNullOrEmpty, which is generally considered better practice than == "". Because you are dealing with text boxes (whose strings are never null) you would still be ok using the old comparison, however.
var textBoxes = new [] {
new { txb = txtUserName, name = "txtUserName" },
new { txb = txtPassw, name = "txtPassw" },
new { txb = txtDatabase , name = "txtDatabase " }
};
var empty = textBoxes.Where(x => x.txb.Text == "").ToList();
if(empty.Any())
{
MessageBox.Show("Please enter " + String.Join(" and ", empty.Select(x => x.name)));
}
Related
I have string value like below example for fax
string fax="1111111111";
I need below result for above string to add special character for fax format like below.
(111)-111-1111
my code for reference because my question going down please help any to get result
var list = (dynamic)null;
if (!String.IsNullOrEmpty(faxdos.medicalRecordsFax) && !String.IsNullOrEmpty(faxdos.fax))
{
list = new List<SelectListItem>
{
new SelectListItem{ Text=String.Format("{0:(###)-###-####}", faxdos.medicalRecordsFax)+" - Medical Records Fax", Value = faxdos.medicalRecordsFax},
new SelectListItem{ Text=String.Format("{0:(###)-###-####}", faxdos.fax), Value = faxdos.fax },
};
}
else if (!String.IsNullOrEmpty(faxdos.medicalRecordsFax))
{
list = new List<SelectListItem>
{
new SelectListItem{ Text=String.Format("{0:(###)-###-####}", faxdos.medicalRecordsFax)+" - Medical Records Fax", Value = faxdos.medicalRecordsFax},
};
}
else if (!String.IsNullOrEmpty(faxdos.fax))
{
list = new List<SelectListItem>
{
new SelectListItem{ Text=String.Format("{0:(###)-###-####}", faxdos.fax), Value = faxdos.fax },
};
}
else
{
list = new List<SelectListItem>
{
new SelectListItem{ Text="", Value = "" },
};
}
// ViewBag.emp = list;
var result = new SelectList(list, "Text", "Value");
return Json(result, JsonRequestBehavior.AllowGet);
well how about just writing code to do it
string fax="1111111111";
string str2 = $"({fax.Substring(0,3)})-{fax.SubString(3,3)}-{fax.Substring(6,4)}";
If you want to use the var result = string.Format("{0:(###)-###-####}", someValue) formatting mechanism, then the value you are formatting needs to be a number, not a string. So you could do something like this:
var telNoString = "1111111111";
if (long.TryParse(telNoString, out var telno))
{
var result = string.Format("{0:(###)-###-####}", telno);
Debug.WriteLine(result);
}
Which will result in (111)-111-1111 in the debug console.
var result = new List<QuickSearchModel>();
var Navmenus = CommonConstants.GetNavItems();
var items = new List<NavMenuItem>();
Navmenus.ForEach(it =>
{
if (it.IsNested)
{
it.menuItems.ForEach(mi => items.Add(new NavMenuItem() { Name = it.Name + "/" + mi.Name, Link = mi.Link }));
}
else {
items.Add(new NavMenuItem() { Name = it.Name, Link = it.Link });
result.Add(new QuickSearchModel() { Id = "1", Title = it.Name, ItemType = it.Name, Route = it.Link });
}
});
return result;
At the end of my code block when I am returning my results, I am expecting 26 items.
In my immediate window, i type items and I see 26 NavMenuItems listed
when I type result, i see 1 QuickSearchModel listed (the 3rd in my items list)
Please see these two images as reference
SOLUTION:
I ultimately did this
public static List<QuickSearchModel> PageListFromNavMenu()
{
var Navmenus = CommonConstants.GetNavItems();
var items = new List<NavMenuItem>();
Navmenus.ForEach(it =>
{
if (it.IsNested)
{
it.menuItems.ForEach(mi => items.Add(new NavMenuItem() { Name = it.Name + "/" + mi.Name, Link = mi.Link }));
}
else {
items.Add(new NavMenuItem() { Name = it.Name, Link = it.Link });
}
});
return PageListFromNavMenu(items);
}
private static List<QuickSearchModel> PageListFromNavMenu(List<NavMenuItem> items)
{
var result = new List<QuickSearchModel>();
items.ForEach(it =>
{
result.Add(new QuickSearchModel() { Id="1", Title = it.Name, ItemType = it.Name, Route = it.Link });
});
return result;
}
It's a shame that I had to run through a 2nd For Loop to get the results but it did work. I wish I could have just have done it in the else block.
Why are you creating a list of NavMenuItems just to convert it to a list of QuickSearchModels? Create QuickSearchModels in your first method (and never create an intermediate List<NavMenuItem>)
public static List<QuickSearchModel> PageListFromNavMenu()
{
var Navmenus = CommonConstants.GetNavItems();
var items = new List<QuickSearchModel>();
Navmenus.ForEach(it =>
{
if (it.IsNested)
{
foreach (var mi in it.menuItems) {
string name = it.Name + "/" + mi.Name;
items.Add(new QuickSearchModel {
Id = "1",
Title = name,
ItemType = name,
Link = mi.Link
});
}
}
else {
items.Add(new QuickSearchModel {
Id = "1",
Title = it.Name,
ItemType = it.Name,
Link = it.Link
});
}
});
return items;
}
Well... Because the code says so. If the NavMenu-item is nested, add something to items colletion, otherwise add it to items and result collection. Obviously you have one root element and 25 child items.
I'm trying to return a list with the number of times a property has a value set.
I'm trying to do this without having to hardcode the value to look for, so if something changes on the backend I won't have to add a new line of code.
Currently I have it working, but I have set the values manually.
listCounts.Add(testList.Count(item => item.title == "Blah"));
listCounts.Add(testList.Count(item => item.title == null));
listCounts.Add(testListt.Count(item => item.title == "test"));
listCounts.Add(testList.Count(item => item.title == "Blarg"));
This works currently but if anything chaanges, i'll have to go in and made changes to the code which is what I am trying to avoid
Depends on what you're trying to do really. It looks like you want the count of wach of those keys (the titles)?
One way would be to group by your title to give the counts, eg.
var listCounts = testList.GroupBy(item => item.title);
As an example of using this:
class Item
{
public string title;
}
static void Main(string[] args)
{
var testList = new List<Item>
{
new Item { title = "Blah" },
new Item { title = "Blah" },
new Item { title = "Blah" },
new Item { title = null },
new Item { title = null },
new Item { title = "test" },
new Item { title = "test" },
new Item { title = "test" },
new Item { title = "test" }
};
var listCounts = testList.GroupBy(item => item.title);
foreach (var count in listCounts)
{
Console.WriteLine("{0}: {1}", count.Key ?? string.Empty, count.Count());
}
Console.ReadKey();
}
The disadvantage is you're getting the count each time - like I said, it depends on what you're trying to achieve. A simple change would make this a dicationary (string, int), whereby each title would be a key, and the value would be the number of times the title appears.
EDIT
To use a dictionary, change the listCounts line to:
var listCounts = testList.GroupBy(t => t.title).ToDictionary(i => i.Key ?? string.Empty, i => i.Count());
(note that a key cannot be null, hence the i.Key ?? string.Empty workaround, should be fine for your purposes)
We don't know what your backend is, but it would seem you need to retrieve the values from it.
//string[] myStrings = new string[] { "Blah", null, "test", "Blarg" };
string[] myStrings = _backEnd.RetrieveValues();
listCounts.Add(testList.Count(item => myStrings.Contains(item)));
I want to create new object with if statement in lambda ForEach, what is this code problem?
List<tblUsersTypeC> usertype = new List<tblUsersTypeC>();
usertype.Add(userToInsertList.ForEach(o =>
{
if ((o.Counts.FollowedBy + o.Counts.Follows + o.Counts.Media) == 0)
new tblUsersTypeC { isPrivite = true, UserName = o.Username, WebsiteUrl = o.Website };
else
new tblUsersTypeC { isPrivite = false, UserName = o.Username, WebsiteUrl = o.Website };
}));
List<T>.ForEach is intended to iterate through the list items and do something, using their current state. Actually, your question is yet another sample, which shows, that ForEach method is unnatural, non-obvious replacement for foreach operator.
To get new list of items, based on items from the current list, use Select/ToList extensions:
var usertype = userToInsertList
.Select(o => new tblUsersTypeC
{
isPrivite = (o.Counts.FollowedBy + o.Counts.Follows + o.Counts.Media) == 0,
UserName = o.Username,
WebsiteUrl = o.Website
})
.ToList();
Try this:
List<tblUsersTypeC> usertype = userToInsertList.Select(o => new tblUsersTypeC()
{
isPrivite = ((o.Counts.FollowedBy + o.Counts.Follows + o.Counts.Media) == 0),
UserName = o.Username,
WebsiteUrl = o.Website
}).ToList();
Use
userToInsertList.Select( o=> (condition) ? value1: value2);
or
userToInsertList.Select( o=> { if(condition) { return value1} else {return value2;}});
List.ForEach doesn't return any thing.
Ok, so I am trying to send POST commands over an http connection, and using JSON formatting to do so. I am writing the program to do this in C#, and was wondering how I would format an array of values to be passed as JSON to the server.
Currently I have this:
new {name = "command" , index = "X", optional = "0"}
Which translates to this in JSON:
"name": "command",
"index": "X",
"optional": "0"
And I want to make an array, called items, where each element contains these three values. So it would essentially be an array of objects, in which the object contains a name, an index, and an optional field.
My guess was that it would be something along the lines of this:
new {items = [(name = "command" , index = "X", optional = "0"),
(name = "status" , index = "X", optional = "0")]}
Which, if it were correct syntax, would translate to this in JSON:
"items":
[
{
"name": "command",
"index": "X",
"optional": "0"
},
{
"name": "status",
"index": "X",
"optional": "0"
}
]
But, evidently I'm doing it wrong. Ideas? Any help is appreciated.
You're close. This should do the trick:
new {items = new [] {
new {name = "command" , index = "X", optional = "0"},
new {name = "command" , index = "X", optional = "0"}
}}
If your source was an enumerable of some sort, you might want to do this:
new {items = source.Select(item => new
{
name = item.Name, index = item.Index, options = item.Optional
})};
You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:
public class Item
{
public string name { get; set; }
public string index { get; set; }
public string optional { get; set; }
}
public class RootObject
{
public List<Item> items { get; set; }
}
Usage:
var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item>
{
new Item { name = "test1", index = "index1" },
new Item { name = "test2", index = "index2" }
};
And in the result you won't have to change things several times if you need to change data-structure.
p.s. Here's very nice tool for complex jsons
Also , with Anonymous types ( I prefer not to do this) -- this is just another approach.
void Main()
{
var x = new
{
items = new[]
{
new
{
name = "command", index = "X", optional = "0"
},
new
{
name = "command", index = "X", optional = "0"
}
}
};
JavaScriptSerializer js = new JavaScriptSerializer(); //system.web.extension assembly....
Console.WriteLine(js.Serialize(x));
}
result :
{"items":[{"name":"command","index":"X","optional":"0"},{"name":"command","index":"X","optional":"0"}]}
new {var_data[counter] =new [] {
new{ "S NO": "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "}
}
};