Add special characters to string value to display Fax Number using C# - c#

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.

Related

Return the number of times a string occurs as a property in a list of custom objects

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)));

how to Add nested object models to the list?

I have some object models like this :
var x= new XModel()
{
end_date = "2017-12-15",
page = 1,
start_date = "2014-12-01",
group_by = new List<string> { "numbers" },
filter = new Filter() { numbers= new List<int> {1620} ,names= null, deleted= null, added = null }
};
or this one :
var y= new YModel
{
Title = "test title",
GenderType = Gender.Men,
Oss = "ALL",
Devices = new List<string> { "11", "12" },
Categories = new List<string> { "11", "12" },
}
i want to add these models to the list, the problem is , i tried to wrote a generic method to add all object models like above to the list.
My current method is :
internal static List<UrlParameter> GetParams<TModel>(this TModel entity)
{
var parameters = new List<UrlParameter>();
foreach (var propertyInfo in entity.GetType().GetProperties())
{
var propVal = propertyInfo.GetValue(entity, null);
if (propVal == null)
{
parameters.Add(new UrlParameter(propertyInfo.Name, ""));
continue;
}
if (propertyInfo.PropertyType.IsGenericType)
{
if (propVal.GetType().IsPrimitiveType())
{
parameters.Add(new UrlParameter(propertyInfo.Name, propVal));
}
else
{
var arr = propVal as IEnumerable;
if (arr.HasArrayContainPrimitiveType())
parameters.Add(new UrlParameter(propertyInfo.Name, $"[{ToJsonArray(arr)}]"));
else
parameters.AddRange(from object obj in arr
select GetParams(obj)
into subparams
select new UrlParameter(propertyInfo.Name, subparams));
}
}
else
{
if (propVal.GetType().IsPrimitiveType())
parameters.Add(new UrlParameter(propertyInfo.Name, propVal));
else
{
var subparams = GetParams(propVal);
parameters.Add(new UrlParameter(propertyInfo.Name, subparams));
}
}
}
return parameters;
}
it works fine for most of my models, but the x where contains filter makes me a problem, the numbers value saved like this filter=numbers%3d%255b1620%255d%2c%2c%2c%2c%2c%2c%2c , and the rest of the fields disappeare.
i want to add numbers, names, deleted and added as key, value parameter nested in filter, can you please help me to fixed this?
I solved my problem by using MultipartFormDataContent class.
it converts all the nested model as they are.

Efficient Way to Populate a List - ASP.NET MVC3

I am new to ASP.NET MVC 3, coming from RoR so I am somewhat familiar with the MVC design pattern.
I created a method that generates a select list to be used in a dropdownfor().
What I have below works but I was wondering if I can make it more efficient or at least do the same thing with less code?
Thanks
public static IEnumerable<SelectListItem> GetDistanceUnits(string distanceUnit)
{
DistanceUnit MilesUnit = new DistanceUnit();
MilesUnit.OptionValue = "mi";
MilesUnit.OptionName = "Miles";
MilesUnit.OptionSelected = "";
DistanceUnit KilometersUnit = new DistanceUnit();
KilometersUnit.OptionValue = "km";
KilometersUnit.OptionName = "Kilometers";
KilometersUnit.OptionSelected = "";
var distanceUnitList = new List<SelectListItem>();
distanceUnitList.Add(new SelectListItem
{
Value = MilesUnit.OptionValue,
Text = MilesUnit.OptionName,
Selected = MilesUnit.OptionSelected == distanceUnit
});
distanceUnitList.Add(new SelectListItem
{
Value = KilometersUnit.OptionValue,
Text = KilometersUnit.OptionName,
Selected = KilometersUnit.OptionSelected == distanceUnit
});
return distanceUnitList.OrderByAscending(c => c.Text);
}
You can use a generator to create your list and a little Linq to project the list.
public static IEnumerable<SelectListItem> GetDistanceUnits(string distanceUnit)
{
var distanceUnitList = GetUnits()
.Select(u =>
new SelectListItem
{
Value = u.OptionValue,
Text = u.OptionName,
Selected = u.OptionSelected == distanceUnit
})
.OrderByAscending(c => c.Text)
.ToList();
return distanceUnitList;
}
private static IEnumerable<DistanceUnit> GetUnits()
{
yield return new DistanceUnit
{
OptionValue = "mi";
OptionName = "Miles";
OptionSelected = "";
};
yield return new DistanceUnit
{
OptionValue = "km";
OptionName = "Kilometers";
OptionSelected = "";
};
}
You can condense the code a little bit more by using a list initializer like this:
var distanceUnitList = new List<SelectListItem> {
new SelectListItem {
Value = MilesUnit.OptionValue,
Text = MilesUnit.OptionName,
Selected = MilesUnit.OptionSelected == distanceUnit
},
new SelectListItem {
Value = KilometersUnit.OptionValue,
Text = KilometersUnit.OptionName,
Selected = KilometersUnit.OptionSelected == distanceUnit
}
};
Otherwise I'd say that's a pretty compact method, nicely organized, and will be very reusable in other areas of your MVC application.
You could make it with a little less code, but I am not sure how much more efficient it would be:
var distanceUnitList = new List<SelectListItem>
{
new SelectListItem{...},
new SelectListItem{...},
};
If you are going to use those local variables only once (to supply data to the SelectListItem), you don't need them. You can do the following:
var distanceUnitList = new List<SelectListItem>() {
new SelectListItem
{
Value = "mi",
Text = "Miles",
Selected = ("" == distanceUnit) // odd code...
},
new SelectListItem
{
Value = "km",
Text = "Kilometers",
Selected = ("" == distanceUnit)
}
};

Linq query for searching an object inside a dictionary having list of lists as values

I'm searching a sorted dictionary with a key of type datetime and values as list of objects. What I need to find is the latest value(based on a property on the object) for each object in the dictionary. My object has 3 properties : a name, a value and a date when it was created. My dictionary is sorted by latest date in descending order.
I have got this working somehow, but I'm sure there is a shortcut for this using LINQ. Please note that I'm using .NET 3.5. Could you please help? Please dont get put off by the huge amount code below as I have added it for clarity and i'm only looking for a linq query to query inside a list of list objects.
Code below:
public void Should_link_recent_data_together()
{
var data = TimeSeriesDataFactoryEx.GetData();
var allAttributes = new List<string>()
{
TimeSeriesConstants.TOTAL_COST_CODE,
TimeSeriesConstants.TOTAL_VALUE_CODE,
TimeSeriesConstants.SOURCE_CODE
};
var latestList = new List<TimeSeries>();
var allValues = data.Values.ToList();
#region HOW DO I DO THIS USING LINQ?
bool found = false;
foreach (var attribute in allAttributes)
{
found = false;
foreach (var tsData in allValues)
{
foreach (var ts in tsData)
{
if (ts.MetricName == attribute && !string.IsNullOrEmpty(ts.MetricValue))
{
latestList.Add(ts);
found = true;
break;
}
}
if (found)
break;
}
}
#endregion
Assert.IsTrue(latestList.Count == 3);
Assert.IsTrue(latestList.Where(x => x.MetricName == TimeSeriesConstants.TOTAL_COST_CODE).First().MetricValue == "1");
Assert.IsTrue(latestList.Where(x => x.MetricName == TimeSeriesConstants.TOTAL_VALUE_CODE).First().MetricValue == "2");
Assert.IsTrue(latestList.Where(x => x.MetricName == TimeSeriesConstants.SOURCE_CODE).First().MetricValue == "gp");
Assert.IsTrue(latestList.Where(x => x.MetricName == TimeSeriesConstants.SOURCE_CODE).First().Quarter == DateTime.Today.AddMonths(-3));
}
internal class TimeSeriesDataFactoryEx
{
public static SortedDictionary<DateTime?,List<TimeSeries>> GetData()
{
return new SortedDictionary<DateTime?, List<TimeSeries>>(new DateComparer())
{
{
DateTime.Today, new List<TimeSeries>()
{
new TimeSeries()
{
Quarter = DateTime.Today,
MetricValue = "1",
MetricName = TimeSeriesConstants.TOTAL_COST_CODE
},
new TimeSeries()
{
Quarter = DateTime.Today,
MetricValue = "2",
MetricName = TimeSeriesConstants.TOTAL_VALUE_CODE
},
new TimeSeries()
{
Quarter = DateTime.Today,
MetricValue = "",
MetricName = TimeSeriesConstants.SOURCE_CODE
}
}
},
{
DateTime.Today.AddMonths(-3), new List<TimeSeries>()
{
new TimeSeries()
{
Quarter = DateTime.Today.AddMonths(-3),
MetricValue = "3",
MetricName = TimeSeriesConstants.TOTAL_COST_CODE
},
new TimeSeries()
{
Quarter = DateTime.Today.AddMonths(-3),
MetricValue = "4",
MetricName = TimeSeriesConstants.TOTAL_VALUE_CODE
},
new TimeSeries()
{
Quarter = DateTime.Today.AddMonths(-3),
MetricValue = "gp",
MetricName =TimeSeriesConstants.SOURCE_CODE
}
}
}
};
}
}
So, assuming I understand your question right, say you have a dictionary like so:
{ Key = "1/1/1900", Value = List Of Objects, of which each has a DateTimeProperty }
...
{ Key = "1/4/1900", Value = List Of Objects, of which each has a DateTimeProperty }
And you are looking to find a set of objects from your dictionary, where it's the latest by time of each key, then you can do this pretty simply with linq:
var latestItems = data.SelectMany(kvp =>
kvp.Value.OrderByDescending(value => value.Quarter).Take(1)
);
This query finds the most recent object in each bucket and then returns that as a single set (not an enumerable of enumerables). You can change the selector inside the SelectMany to find elements in each set as much as you want, as long as you return an IEnumerable from that callback.

How to set the static text into JsonResult?

I found the following code example (from Telerik ) that I'm trying to understand.
What I need to do is somehow to set static text into JsonResult (e.g.Text ="Abc" and Value="123")
public ActionResult _AjaxLoading(string text)
{
Thread.Sleep(1000);
using ( var nw = new NorthwindDataContext() )
{
var products = nw.Products.AsQueryable();
if ( text.HasValue() )
{
products = products.Where((p) => p.ProductName.StartsWith(text));
}
return new JsonResult { Data = new SelectList(products.ToList(), "ProductID", "ProductName") };
}
}
public ActionResult _AjaxLoading(string text
{
var data = new { Text= "123", Value= "Abc"};
return Json(data, JsonRequestBehavior.AllowGet);
}
If it is an HTTPGet method, You should specify JsonRequestBehavior.AllowGet as second parameter to return JSon data from a GET method
It looks like you are in need of this:
return new JsonResult { Data = new { Text="Abc", Value="123", Produtcs= new SelectList(products.ToList(), "ProductID", "ProductName") }};
Is this what you are looking for
return new JsonResult { Text = "Abc", Value="123" };
If you want to add a new element to the drop down at start then
var editedProducts = new SelectList(products.ToList(), "ProductID","ProductName" ).ToList();
editedProducts.insert(0, new SelectListItem() { Value = "123", Text = "Abc" });
return new JsonResult { Data = editedProducts };

Categories

Resources