parsing string for dropdownlist options - c#

I have a string (q.ADDLOption) with values like
Select,|IE,IE|Safari,Safari|Chrome,Chrome|
I want to parse it to be the options in a dropdownlist
Optionddl oddl = q.ADDLOption.Split('|').ToList<Optionddl>(); <== this is giving error
I have also a class
public class Optionddl
{
public string text { get; set; }
public string value { get; set; }
}

This might do the trick for you
List<Optionddl> oddl = q.ADDLOption.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => new Optionddl
{
text = x.Split(',')[0],
value = x.Split(',')[1]
})
.ToList<Optionddl>();
The first problem with the code is q.ADDLOption.Split.ToList is going to return a list and not an object of Optionddl. Secondly we cannot directly convert an array of string[] to List because 'string[]' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList(System.Collections.Generic.IEnumerable)' has some invalid arguments would be the error. Lastly it is optional to create ToList or ToList<Optionddl>.
Hope this helps

Because Optionddl is not something can be converted to a List.
Consider this:
List<Optionddl> oddl = q.ADDLOption.Split(new string[]{'|'}).ToList<Optionddl>();

Alternatively you can create some implicit/explicit operators :
public class Optionddl
{
public string text { get; set; }
public string value { get; set; }
public static implicit operator string(Optionddl option)
{
return option.text + "," + option.value;
}
public static implicit operator Optionddl(string str)
{
string[] extracted = str.Split(",");
return new Optionddl { text = extracted[0], value = extracted[1] };
}
}
This way you can make something like :
Optionddl meOption = new Optionddl { value = "IE", text = "IE" };
string meOptionString = meOption; // result of meOptionString = "IE,IE"
meOption = meOptionString; // result of meOption = { text = "IE", value = "IE" }

Related

How to use constructor to initialize list of objects containing the array

right now, I use this command to initialize a list of objects and it works fine.
public class RelatedBlog
{
public string trekid { get; set; }
public string imagepath { get; set; }
public RelatedBlog(string trekid, string imagepath)
{
this.trekid = trekid;
this.imagepath = imagepath;
}
}
trek.relatedblog = new List<RelatedBlog>
{
new RelatedBlog("trekid", "../Images/image.jpg"),
};
However, lately I have decided that instead of single string as a first property, I want to have an array of several strings - with the size up to 4 (but it can be also fixed and I can enter nulls during initialization). This is the code I am using, but it doesnt work, it expects some more "(" when I call the constructor.
public class RelatedBlog
{
public string[] trekid { get; set; }
public string imagepath { get; set; }
public RelatedBlog(string[] trekid, string imagepath)
{
this.trekid = trekid;
this.imagepath = imagepath;
}
}
trek.relatedblog = new List<RelatedBlog>
{
new RelatedBlog({"string1", "string2"}, "../Images/image.jpg"),
};
Can someone advise me where I make a mistake and how to initialize this list properly. Thanks a lot
Use:
trek.relatedblog = new List<RelatedBlog>
{
new RelatedBlog(new[] {"string1", "string2"}, "../Images/image.jpg")
};
You are using implicitly typed array, the compiler can detect the type inside array but you have to inform it that you are passing an array:
var arr1 = new[] { "hello", "world" };
is equal to
var arr2 = new string [] { "hello", "world" };

create querystring using lambda from List T

i am having some difficulties creating a proper select.
i have my custom class:
internal class classA{
internal string FieldName { get; set; }
internal string FieldValue { get; set; }
internal bool IncludeInChecksum { get; set; }
}
what i am trying to do is to build and concatinate a querystring using the class list from above.
for the following object:
List<classA> requestParams = ...
the query string should look like:
a=1&b=2&c=3
ordered by FieldName ascending
where IncludeInChecksum = true
FieldName = FieldValue
preMD5= requestParams
.Where(x=>x.IncludeInChecksum)
.OrderBy(y=>y.FieldName)
.Aggregate((i,j)=>(i.FieldName+ "=" +j.FieldValue));
this is where i am stuck.
thanks in advance
I will try to get all name=value strings with the help of the Select() method. And then convert the result to array. After that just use String.Join() method to get the desired result.
Join(String, String[]) concatenates all the elements of a string array, using the specified separator between each element.
var preMD5= requestParams
.Where(x => x.IncludeInChecksum)
.OrderBy(y => y.FieldName)
.Select(z => string.Format("{0}={1}", z.FieldName, z.FieldValue))
.ToArray();
preMD5 = string.Join("&", preMD5);
Aggregate aggregates values from different rows. You need to combine values from different fields. For this you use Select:
requestParms.Where(...).OrderBy(...).Select(f=>f.FieldName+"="+f.FieldValue)
This will return an IEnumerable of name=value strings. You can use string.Join to combine them into one string.
I know it's been answered,
but still I wanted to provide my solution.
I used a dedicated method to build the query string parameter,
and an extension method to concat it all.
Hope this helps.
public class classA
{
internal string FieldName { get; set; }
internal string FieldValue { get; set; }
internal bool IncludeInChecksum { get; set; }
public classA(string fieldName, string fieldValue, bool includeInChecksum)
{
this.FieldName = fieldName;
this.FieldValue = fieldValue;
this.IncludeInChecksum = includeInChecksum;
}
public string ToQueryString()
{
return string.Format("{0}={1}",
this.FieldName,
this.FieldValue);
}
public void Test()
{
var list = new List<classA> {
new classA("A", "1", true) ,
new classA("D", "4", true) ,
new classA("B", "2", false) ,
new classA("C", "3", true)
};
var result = list.
Where(o => o.IncludeInChecksum).
OrderBy(o => o.FieldName).
Select(o => o.ToQueryString()).
ToStringEx("&");
}
}
public static class ExtensionMethods
{
public static string ToStringEx<T>(this IEnumerable<T> items, string separetor = ",")
{
if (items == null)
{
return "null";
}
return string.Join(separetor, items.Select(o => o != null ? o.ToString() : "[null]").ToArray());
}
}

Convert Array to custom object list c#

I have a array:-
private string[][] barValues = new string[][] { new string[]{ "1.9", "5.8", "4.8", "Since Inception", "24-Jan 2014 to 24 Jun 2014" },
new string[]{"1.2", "16.5","9.8", "Year to date","01-Apr 2014 to 24-Jun 2014" },
new string[]{"11.6","28.8","23.5","Last quarter","01-Jan to 24-Jun 2014"} };
I want to convert this array into my custom list :-
List<Portfolio> list = new List<Portfolio>();
I tried doing :-
List<Portfolio> list=myArray.Cast<Portfolio>().ToList();
But I get a error:-
System.InvalidCastException: Cannot cast from source type to
destination type.
How do I do this conversion?
You will need to use the Select operator and assign your array of strings to your Portfolio object. Something like this:
myArray.Select(array => new Portfolio { Field1 = array[0], Field2 = array[1] }).ToList()
There is no "magic" conversion from string[] to your class PortFolio, you have to do it manually.
This could work:
List<Portfolio> portFolioList = barValues
.Select(sArr => new Portfolio
{
Values = sArr.Take(3).Select(double.Parse).ToList(),
Name = sArr.Skip(3).First(),
TimeSpan = sArr.Last()
}).ToList();
If you have a class like this:
public class Portfolio
{
public List<double> Values { get; set; }
public string Name { get; set; }
public string TimeSpan { get; set; }
}
Convert Array to string try this way
string[] arr = ...
List<object> list= new List<object>(arr);
foreach(object obj in arr)
list.add(obj);
var converted = barValues.Select(a => new {Value1 = a[0], Value2= a[1]}).ToArray();
This gives you an array of anonymous objects. Just replace my anonymous constructor with your constructor of Portfolio. Lambda variable a is the array that contains the string values.
Create a constructor taking the items from barValues and iterator over those.
like:
class PortFolio()
{
PortFolio(string e1, string e2, string e3, string period, string date)
{
// Copy to properties.
}
...
}
Then in the code for copying:
foreach (var barValue in barValues)
{
list.Add(new PortFolio(barValue[0], barValue[1], barValue[2], barValue[3], barValue[4]); }
}
C# is a strongly typed language. There is no out of the box way to magically cast a bunch of string into an object.
A correct way to do what you want is to first add a constructor on your Portfolio class that takes an array of strings and assign its values to your instance properties:
class Portfolio
{
public string Value1 { get; set; }
public string Value2 { get; set; }
public string Value3 { get; set; }
public string Method { get; set; }
public string Period { get; set; }
public Portfolio(string[] values)
{
if (values != null)
{
this.Value1 = values.ElementAtOrDefault(0);
this.Value2 = values.ElementAtOrDefault(1);
this.Value3 = values.ElementAtOrDefault(2);
this.Method = values.ElementAtOrDefault(3);
this.Period = values.ElementAtOrDefault(4);
}
}
}
You can then use linq to build your list :
var portfoliosList = barValues.Select(values => new Portfolio(values)).ToList();
If required, you can do additional work in the constructor, for instance converting the values to decimal, the method to an Enum and the period as a couple of DateTime.
If you cannot modify the Portfolio class, because it's a third party component or out of your scope, you can create a factory class with a method containing that logic :
static class ProtfolioFactory
{
static public Portfolio BuildPortfolio(string[] values)
{
var portfolio = new Portfolio();
if (values != null)
{
portfolio.Value1 = values.ElementAtOrDefault(0);
portfolio.Value2 = values.ElementAtOrDefault(1);
portfolio.Value3 = values.ElementAtOrDefault(2);
portfolio.Method = values.ElementAtOrDefault(3);
portfolio.Period = values.ElementAtOrDefault(4);
}
return portfolio;
}
}
The linq query then becomes :
var list = barValues.Select(values => ProtfolioFactory.BuildPortfolio(values)).ToList();

Converting an array to object

I have 2 types of string: Mer and Spl
// Example
string testMer = "321|READY|MER";
string testSpl = "321|READY|SPL";
Then I will split them:
var splitMer = testMer.Split('|');
var splitSpl = testSpl.Split('|');
I have an object to save them
public class TestObject
{
public int id { get; set; }
public string status { get; set; }
public string type { get; set; }
}
Question: How to convert the Array into the TestObject?
var converted = new TestObject
{
id = int.Parse(splitMer[0]),
status = splitMer[1],
type = splitMer[2]
};
You will need to add some error checking.
var values = new List<string> { "321|READY|MER", "321|READY|SPL" };
var result = values.Select(x =>
{
var parts = x.Split(new [] {'|' },StringSplitOptions.RemoveEmptyEntries);
return new TestObject
{
id = Convert.ToInt32(parts[0]),
status = parts[1],
type = parts[2]
};
}).ToArray();
You just need to use object initializers and set your properties.By the way instead of storing each value into seperate variables, use a List.Then you can get your result with LINQ easily.
var splitMer = testMer.Split('|');
var testObj = new TestObject();
testObj.Id = Int32.Parse(splitMer[0]);
testObj.Status = splitMer[1];
testObj.type = splitMer[2];
How about adding a Constructor to your Class that takes a String as a Parameter. Something like this.
public class TestObject
{
public int id { get; set; }
public string status { get; set; }
public string type { get; set; }
public TestObject(string value)
{
var valueSplit = value.Split('|');
id = int.Parse(valueSplit[0]);
status = valueSplit[1];
type = valueSplit[2];
}
}
Usage:
TestObject tst1 = new TestObject(testMer);
TestObject tst2 = new TestObject(testSpl);

Unable to cast a list

I am getting a error in the line below.
temp.day1_veh_p = string.Join(Environment.NewLine, day1.Where(x => x.plannedTriips == 1).Select(x => new {value=x.vehicleNumber+":"+x.shiftCompletedOn }).Cast<string>().ToArray());
Th error Message being
Unable to cast object of type '<>f__AnonymousType0`1[System.String]' to type 'System.String'.
The list day1 is of type
public class tripDetails
{
public string accountID { get; set; }
public string supplierName { get; set; }
public string supplierCode { get; set; }
public DateTime shiftFrom { get; set; }
public DateTime shiftTo { get; set; }
public int plannedTriips { get; set; }
public int actualTrips { get; set; }
public DateTime forDate { get; set; }
public string vehicleNumber { get; set; }
public string shiftCompletedOn { get; set; }
public class Comparer : IEqualityComparer<tripDetails>
{
public bool Equals(tripDetails x, tripDetails y)
{
return x.supplierCode == y.supplierCode;
}
public int GetHashCode(tripDetails obj)
{
return (obj.supplierCode).GetHashCode();
}
}
}
What exactly Am i doing wrong??
The problem is the new { value = ... }
Replace:
Select(x => new {value=x.vehicleNumber+":"+x.shiftCompletedOn }).Cast<string>()
with
Select(x => x.vehicleNumber+":"+x.shiftCompletedOn)
and you're sorted. You won't need the Cast<string>() at all.
Your original code creates, for each record, a new instance of an anonymous type that has a member called value with the string desired; the second version just creates the string.
In a way, it is no different to trying this:
class Foo
{
public string Bar {get;set;}
}
...
var foo = new Foo { Bar = "abc" };
string s = (string)foo; // doesn't compile
Yes, an anonymous type is not a string, so replace this
.Select(x => new { value = x.vehicleNumber + ":" + x.shiftCompletedOn })
with
.Select(x => x.vehicleNumber + ":" + x.shiftCompletedOn)
Then you can use the query(you don't need to create a new array) for string.Join.
It's also helpful to use multiple lines, it makes your code much more readable:
var vehicles = day1.Where(x => x.plannedTriips == 1)
.Select(x => x.vehicleNumber + ":" + x.shiftCompletedOn);
string str = string.Join(Environment.NewLine, vehicles);
Replace this
(x => new {value=x.vehicleNumber+":"+x.shiftCompletedOn }).Cast<string>()
by this
(x => String.Format("{0}\:{1}", x.vehicleNumber, x.shiftCompletedOn))
When you are doing new { ... } you are creating items of anonymous type and then (Cast<string()) trying explicitly cast to string and such conversion is not defined - youn ends up with appropriate exception.

Categories

Resources