How do i split a value in model class - c#

How do i split a value in model class.
in list[0].key = 1 and list[0].value = 1_5
here is the code:
if (data.Things.Count != 0)
{
var ans = new List<QuestionModel>();
ans = data.Things.Select(item =>
{
return new QuestionModel()
{
QuestionId = Convert.ToInt32(item.Key),
AnswerId = Convert.ToInt32(item.Value),
};
}).ToList();
}
here i want to split the value.i.e. in AnswerId want only 5.

If you always want the part after the underscore, and it's always an underscore in the format of item.Value, you can do this:
item.Value.Split('_')[1];
This splits the string on the _ and then takes the second part (e.g. what is after the _).
So the complete line of code would be:
AnswerId = Convert.ToInt32(item.Value.Split('_')[1]),
I would add that the fact you are having to do something this clunky is perhaps a symptom of your model not being a good fit to your domain - if you are able to refactor your model such that you don't have to do this and the field in question contains only the data you are interested in then your solution would be cleaner and more easily maintainable.

Come on. Value is a string value right? Did you look at string class what methods does it have? There is a method called split. Read more here: https://msdn.microsoft.com/en-US/library/b873y76a(v=vs.110).aspx
In short:
string value = "1_5";
string[] arr = value.Split('_');
//now arr[0] is "1" and arr[1] is "5"
int i = Convert.ToInt(arr[1]);

I'm not entirely sure, what you're trying to achieve, but I think you want to split the string "1_5" and retrieve just the "5". This can be achieved using string.Split():
(item.Value.Split('_'))[1]

Related

Substring continue to search until specific character

I am getting a string at the run time. The string is in JSON format( key value pair). One of the key is "userId". I need to retrieve the value of userId. The problem is I don't know the position of "userId" key. The string can look like {"name":"XX", "userId":"YYY","age":"10"} or it can look like {"age":"10", "name":"XX", "userId":"YYY"} or it can look like this {"age":"10"}
I am thinking of using substring()
var index = myString.IndexOf("userId\":\"");
if(index != -1){
myString.Subtring(index, ???)//How to specify the length here
}
I am not sure, how to say continue until you find next " (double quote)
If only userId attribute is planned to use, you can simply declare an object with userId member and deserialize json. any other attributes will be omitted during deserialization.
class UserIDObj
{
public string UserId { get; set; }
}
var obj = JsonConvert.DeserializeObject<UserIDObj>("{\"name\":\"XX\", \"userId\":\"YYY\",\"age\":\"10\"}");
string usrID = obj.UserId;
Answer given by #Wiktor Stribiżew also works like a charm. I am pasting his solution.
System.Text.RegularExpressions.Regex.Match(myString, "\"userId\":\"([^\"]+)").Groups[1].Value
You could do this:
var needle = "\"userId\":"; // also you forgot to escape the quote here
var index = myString.IndexOf(needle);
if(index != -1){
var afterTheUserId = myString.Substring(index + needle.Length);
var quoteIndex = afterTheUserId.IndexOf('"');
// do what you want with quoteIndex
}
But as Eric Philips and PhonicUK said, you should use a proper JSON parser instead of writing your own string functions.

Filter array of string and get only matching ones with searched string

I have an array of string and I want to get back from it a filtered array that contains only those strings that match the searched string.
string[] myValues = {"School.Report1", "School.Report2", "School.Report3", "House.Report1", "House.Report2"};
string myFilter = "School";
string[] filteredValues = myValues.Filter(myFilter); // or something similar
filteredValues must contains only: "School.Report1", "School.Report2", "School.Report3".
-- EDIT --
I prefer a non-LINQ approach if possibile. Otherwise I know that this question can be answered with the solution proposed here: filter an array in C#.
If you can't use LINQ you can still use Array.FindAll:
string[] filteredValues = Array.FindAll(myValues, s => s.Contains(myFilter));
or maybe you want to keep only all strings which first token(separated by dot) is School:
string[] filteredValues = Array.FindAll(myValues, s => s.Split('.')[0] == myFilter);
One possible answer is to make an IComparer that sorts the array by the matching value (if it contains filter return 1 else return 0) then find the first item outside the filter and make another array with the values up the one before that point.

C# find numbers between two dots?

So, basically what i need is to get numbers that are between second and third dot.
Example:
I type in my textbox "1.1.1.1" or "183.312.21.132", I click a button and in the seconds textbox I get numbers that are between second and third dot. Like for first one it would be "1" and for seconds one it will be "21"
Sorry for bad English. Thanks!
try split
"1.1.1.1".Split('.')[2]
or
"183.312.21.132".Split('.')[2]
returns a string[] and index 2 would be the third number
Use string split:
"183.312.21.132".Split(".")[index_of_the_dot_before_desired_numbers]
i.e.
"183.312.21.132".Split('.')[2] = "21"
UPD:
if you need a range between dots, you can use LINQ:
var startDotIndex=1;
var endDotIndex=3;
"183.312.21.132".Split('.').Skip(startDotIndex).Take(endDotIndex-startDotIndex).ToArray()
will return ["312", "21"];
string digits[] = "1.2.3.4".Split(".");
Use elsewhere with:
digits[0]
digits[1]
It sounds like you need the String object's Split method see below:
string foo = "183.312.21.132";
string[] foos = foo.Split('.');
from here you can do many different things such as loop through your array and grab values or if you know exactly what index you are looking for you can simply request it straight from the array such as:
string bar = foo.Split('.')[2]; // gives you "21"
var foo = "192.168.0.1";
var digs = foo.Split(".");
var nums = int.Parse(digs[2]);

string.insert multiple values. Is this possible?

Im still learning in C#, and there is one thing i cant really seem to find the answer to.
If i have a string that looks like this "abcdefg012345", and i want to make it look like "ab-cde-fg-012345"
i tought of something like this:
string S1 = "abcdefg012345";
string S2 = S1.Insert(2, "-");
string S3 = S2.Insert(6, "-");
string S4 = S3.Insert.....
...
..
Now i was looking if it would be possible to get this al into 1 line somehow, without having to make all those strings.
I assume this would be possible somehow ?
Whether or not you can make this a one-liner (you can), it will always cause multiple strings to be created, due to the immutability of the String in .NET
If you want to do this somewhat efficiently, without creating multiple strings, you could use a StringBuilder. An extension method could also be useful to make it easier to use.
public static class StringExtensions
{
public static string MultiInsert(this string str, string insertChar, params int[] positions)
{
StringBuilder sb = new StringBuilder(str.Length + (positions.Length*insertChar.Length));
var posLookup = new HashSet<int>(positions);
for(int i=0;i<str.Length;i++)
{
sb.Append(str[i]);
if(posLookup.Contains(i))
sb.Append(insertChar);
}
return sb.ToString();
}
}
Note that this example initialises StringBuilder to the correct length up-front, therefore avoiding the need to grow the StringBuilder.
Usage: "abcdefg012345".MultiInsert("-",2,5); // yields "abc-def-g012345"
Live example: http://rextester.com/EZPQ89741
string S1 = "abcdefg012345".Insert(2, "-").Insert(6, "-")..... ;
If the positions for the inserted strings are constant you could consider using string.Format() method. For example:
string strTarget = String.Format("abc{0}def{0}g012345","-");
string s = "abcdefg012345";
foreach (var index in [2, 6, ...]
{
s = s.Insert(index, "-");
}
I like this
StringBuilder sb = new StringBuilder("abcdefg012345");
sb.Insert(6, '-').Insert(2, '-').ToString();
String s1 = "abcdefg012345";
String seperator = "-";
s1 = s1.Insert(2, seperator).Insert(6, seperator).Insert(9, seperator);
Chaining them like that keeps your line count down. This works because the Insert method returns the string value of s1 with the parameters supplied, then the Insert function is being called on that returned string and so on.
Also it's worth noting that String is a special immutable class so each time you set a value to it, it is being recreated. Also worth noting that String is a special type that allows you to set it to a new instance with calling the constructor on it, the first line above will be under the hood calling the constructor with the text in the speech marks.
Just for the sake of completion and to show the use of the lesser known Aggregate function, here's another one-liner:
string result = new[] { 2, 5, 8, 15 }.Aggregate("abcdefg012345", (s, i) => s.Insert(i, "-"));
result is ab-cd-ef-g01234-5. I wouldn't recommend this variant, though. It's way too hard to grasp on first sight.
Edit: this solution is not valid, anyway, as the "-" will be inserted at the index of the already modified string, not at the positions wrt to the original string. But then again, most of the answers here suffer from the same problem.
You should use a StringBuilder in this case as Strings objects are immutable and your code would essentially create a completely new string for each one of those operations.
http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx
Some more information available here:
http://www.dotnetperls.com/stringbuilder
Example:
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder("abcdefg012345");
sb.Insert(2, '-');
sb.Insert(6, '-');
Console.WriteLine(sb);
Console.Read();
}
}
}
If you really want it on a single line you could simply do something like this:
StringBuilder sb = new StringBuilder("abcdefg012345").Insert(2, '-').Insert(6, '-');

how do I create an enum from a string representation? c#

im trying to pass back from a user control a list of strings that are part of an enum, like this:
<bni:products id="bnProducts" runat="server" ProductsList="First, Second, Third" />
and in the code behid do something like this:
public enum MS
{
First = 1,
Second,
Third
};
private MS[] _ProductList;
public MS[] ProductsList
{
get
{
return _ProductList;
}
set
{
_ProductList = how_to_turn_string_to_enum_list;
}
}
my problem is I dont know how to turn that string into a list of enum, so what should be "how_to_turn_string_to_enum_list"? or do you know of a better way to use enums in user controls? I really want to be able to pass a list that neat
This is a short solution, but it doesn't cover some very important things like localization and invalid inputs.
private static MS[] ConvertStringToEnumArray(string text)
{
string[] values = text.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
return Array.ConvertAll(values, value => (MS)Enum.Parse(typeof(MS), value));
}
You need to look at the System.Enum.Parse method.
Enum.Parse is the canonical way to parse a string to get an enum:
MS ms = (MS) Enum.Parse(typeof(MS), "First");
but you'll need to do the string splitting yourself.
However, your property is currently of type MS[] - the value variable in the setter won't be a string. I suspect you'll need to make your property a string, and parse it there, storing the results in a MS[]. For example:
private MS[] products;
public string ProductsList
{
get
{
return string.Join(", ", Array.ConvertAll(products, x => x.ToString()));
}
set
{
string[] names = value.Split(',');
products = names.Select(name => (MS) Enum.Parse(typeof(MS), name.Trim()))
.ToArray();
}
}
I don't know whether you'll need to expose the array itself directly - that depends on what you're trying to do.
string[] stringValues = inputValue.Split(',');
_ProductList = new MS[stringValues.Length];
for (int i=0;i< stringValues.Length;i++)
_ProductList[i] = (MS) Enum.Parse(typeof(MS), stringValues[i].Trim());
(updated my code because I misread your code)
Mark your enum with the [Flags] attribute, and combine flags instead of an array of enum values.

Categories