Splitting text into an array of 4 - c#

I want to split text, using a char, so that I can create an object from it.
string s = "Domain_FieldName";
//string s = "Domain_Schema_TableName_FieldName";
//string s = "Domain_Schema_FieldName";
var x = s.Split(new[] {'_'}, StringSplitOptions.None);
var xx = new Response()
{
Value = "test",
DataType = "string",
Domain =
Schema =
TableName =
FieldName =
};
So, the issue is that the string to be split, could vary in length.
But I need the string to be split so that it could map to the response object fields.
I need to have a generic way to populate the response object.
So as an example, if only "Domain_FieldName" is specified, it needs to know to pass Domain to Domain on the response and FieldName to FieldName on the response, and Schema and TableName should get an empty string

You can do something like this:
var x = s.Split(new[] { '_' }, StringSplitOptions.None);
var xx = new Response
{
Value = "test",
DataType = "string",
Domain = x.Length > 0 ? x[0] : null,
Schema = x.Length > 1 ? x[1] : null,
TableName = x.Length > 2 ? x[2] : null,
FieldName = x.Length > 3 ? x[3] : null
};

Use C# Split function
string s = "Domain_Schema_TableName_FieldName";
string[] substring= s.Split('_');
The above code will split the string Domain_Schema_TableName_FieldName into different parts using the delimiter _ and will save the substrings in a string array called substring

Try checking the length of the split Array, before setting variables. (And set a default value, if it's too short)
var xx = new Response()
{
Value = "test";
DataType = "string";
Domain = (x.Length >= 1)?x[0]:"";
Schema = (x.Length >= 2)?x[1]:"";
TableName = (x.Length >= 3)?x[2]:"";
FieldName = (x.Length >= 4)?x[3]:"";
};
(also: s.Split("_") or s.Split('_') would work just as well)
EDIT:
I didn't see, that you only wanted the last 4 fields filled. Changed code
2nd EDIT:
I also didn't see that the Order of strings may be different (i.e. Example 1 vs. Example 3) . In that case i can't help you unless you can specify, how to determine which string needs to go into which field.

try this
string s = "Domain_FieldName";
var x = s.Split(new[] { '_' }, StringSplitOptions.None);
var xx = new Response
{
Value = "test",
DataType = "string",
Domain =x[0],
Schema ="",
TableName ="",
FieldName = x[1]
};

From your examples seems like Domain is always first, and FieldName always last:
string s = "Domain_FieldName";
//string s = "Domain_Schema_TableName_FieldName";
//string s = "Domain_Schema_FieldName";
var x = s.Split('_');
var xx = new Response()
{
Value = "test",
DataType = "string",
Domain = x[0]
Schema = x.Length > 2 ? x[1] : "";
TableName = x.Length > 3 ? x[2] : "";
FieldName = x.Length > 1 ? x.Last() : "";
};

Related

How to get a and b value from a text like axb?

I am facing a problem with how to get a specific string value from a text. For example: for a given string
"400X500 abc"
How can I get some string from that text like:
string width = "400"
string height = "500"
Thank you so much for your help.
Best Regards,
Cherry Truong
You can try regular expressions in order to extract numbers
using System.Text.RegularExpressions;
...
string source = "400X500 abc";
string[] numbers = Regex
.Matches(source, "[0-9]+")
.OfType<Match>()
.Select(match => match.Value)
.ToArray();
string width = numbers.ElementAtOrDefault(0) ?? "";
string height = numbers.ElementAtOrDefault(1) ?? "";
Or (if you want to be sure that X delimiter is present)
Match match = Regex
.Match(source, #"([0-9]+)\s*X\s*([0-9]+)", RegexOptions.IgnoreCase);
string width = match.Success ? match.Groups[1].Value : "";
string height = match.Success ? match.Groups[2].Value : "";
You can try something like this:
string data = "400X500 abc";
string[] splitData = data.TrimEnd('a', 'b', 'c').Trim().Split('X');
string width = splitData[0] ?? string.Empty;
string height = splitData[1] ?? string.Empty;
If you can assume that it will always be in that format, you can do something like this:
string raw = "400X500";
string width = raw.Substring(0, raw.IndexOf("X"));
string height = raw.Substring(raw.IndexOf("X") + 1);
Now width="400" and height=500.
Assuming the text is always going to be in the format "100X200 aabdsafgds", then a working solution would look something like:
var value = "100X200 aabdsafgds";
var splitValues = value.Split(new[] { 'X', ' ' }, StringSplitOptions.RemoveEmptyEntries);
var value1 = splitValues[0];
var value2 = splitValues[1];
I assume the input string is always in the same format.
"heightXwidth abc"
var value = "400X500 abc";
var vals = value.Trim().Split('X');
var height = new string(vals[0] == null ? "0".ToArray() : vals[0].Where(char.IsDigit).ToArray());
var width = new string(vals[1] == null ? "0".ToArray() : vals[1].Where(char.IsDigit).ToArray());
I'm sure you could adjust as needed.
EDIT:
I adjusted the code to avoid the issues as pointed out in the comments and ensure you only get the numbers from the string

Get the substring of the non conditional part

I have this string for example:
2X+4+(2+2X+4X) +4
The position of the parenthesis can vary. I want to find out how can I extract the part without the parenthesis. For example I want 2X+4+4. Any Suggestions?
I am using C#.
Try simple string Index and Substring operations as follows:
string s = "2X+4+(2+2X+4X)+4";
int beginIndex = s.IndexOf("(");
int endIndex = s.IndexOf(")");
string firstPart = s.Substring(0,beginIndex-1);
string secondPart = s.Substring(endIndex+1,s.Length-endIndex-1);
var result = firstPart + secondPart;
Explanation:
Get the first index of (
Get the first index of )
Create two sub-string, first one is 1 index before beginIndex to remove the mathematical symbol like +
Second one is post endIndex, till string length
Concatenate the two string top get the final result
Try Regex approach:
var str = "(1x+2)-2X+4+(2+2X+4X)+4+(3X+3)";
var regex = new Regex(#"\(\S+?\)\W?");//matches '(1x+2)-', '(2+2X+4X)+', '(3X+3)'
var result = regex.Replace(str, "");//replaces parts above by blank strings: '2X+4+4+'
result = new Regex(#"\W$").Replace(result, "");//replaces last operation '2X+4+4+', if needed
//2X+4+4 ^
Try this one:
var str = "(7X+2)+2X+4+(2+2X+(3X+3)+4X)+4+(3X+3)";
var result =
str
.Aggregate(
new { Result = "", depth = 0 },
(a, x) =>
new
{
Result = a.depth == 0 && x != '(' ? a.Result + x : a.Result,
depth = a.depth + (x == '(' ? 1 : (x == ')' ? -1 : 0))
})
.Result
.Trim('+')
.Replace("++", "+");
//result == "2X+4+4"
This handles nested, preceding, and trailing parenthesis.

parse querystring in asp.net with mutiple values seperated by colon

I have a strange querystring formation that I need to parse. The format is - key=N:1042,B:10,C:200 . I havent encountered this format in the past, is there an easy way to extract the values of "N" , "B" , and "C" in asp.net?
Thanks!
Just a suggestion, you can also use LINQ to get parsed/split values. Like following.
var val = Request.QueryString.Get("key"); //"N:1042,B:10,C:200"
if (val.IndexOf(",") != -1)
{
var parsedValue = (from m in val.Split(',')
where m.Split(':').Count() == 2
select new { key = m.Split(':')[0], value = m.Split(':')[1] });
}
Output
use the Split Method :
string key = "N:1042,B:10,C:200";
string[] values = key.Split(',');
for (int i = 0; i < values.Length; i++)
{
var nbc = values[i].Split(':')[1];
//Do something with your var..
}
more info here : Split method MSDN
Very simply:
var val = Request.QueryString.Get("key");
var terms = val.Split(',');
foreach (var term in terms)
{
var pair = term.Split(':');
var key = pair[0];
var v = pair[1];
}

select case in Datatable datarow in Linq

I have a DataTable which is having 3 columns like IsMonday,Istuesday and IsWednesday,both are string fields having datas like Y and N.I wanted to take each row and return the result in a string.What i wanted to get is,
if a row is Y,N,Y then the output will be 1 3,two is blank since it is N
if a row is N,N,Y then the output will be 3,one and two is blank since it is N
like this,any idea using Linq case statement or any other way
Considering that you have a collection of rows returned from your database that looks something similar to this List.
var entity = new List<Entity>()
{
new Entity(){ IsMonday = "Y", IsTuesday = "N", IsWednesday = "Y"},
new Entity() { IsMonday = "N", IsTuesday = "N", IsWednesday = "Y"},
new Entity() { IsMonday = "Y", IsTuesday = "Y", IsWednesday = "N"}
};
To get the expected result you can use a code something like this
foreach (var e in entity)
{
var a = e.IsMonday.Equals("y", StringComparison.OrdinalIgnoreCase) ? "1" : " ";
var b = e.IsTuesday.Equals("y", StringComparison.OrdinalIgnoreCase) ? "2" : " ";
var c = e.IsWednesday.Equals("y", StringComparison.OrdinalIgnoreCase) ? "3" : " ";
var s = String.Format("{0} {1} {2}", a, b, c);
}
Here the variable 's' contains the result string.
This will turn all the rows into List<string>:
var columnNames = new[]{"IsMonday","Istuesday","IsWednesday"};
var rows = dt.AsEnumerable()
.Select(row=>string.Join("",
dt.Columns.Cast<DataColumn>()
.Where(col=>columnNames.Contains(col.ColumnName))
.Select(col=>row.Field<string>(col) == "N" ? " " :
(col.Ordinal+1).ToString()))).ToList();
Note that you said something like that "N" will be replaced with a blank, but looks like you mean a space, so I used a space instead, you can just replace it to whatever you want.
If you just want to convert a specific row to a string, it's very similar like this:
//the input is row
var rowString = string.Join("",
dt.Columns.Cast<DataColumn>()
.Where(col=>columnNames.Contains(col.ColumnName))
.Select(col=>row.Field<string>(col) == "N" ? " " :
(col.Ordinal+1).ToString())).ToList();

Find MAX Number from a String List with C#

I have a string list having characters with numbers. I just wanted to split the string to get the number and later I need to find the max number from that splitted number list.
Match String
abc
Example List Values
abc9
abc100
abc999
abc
Result
abc1000
I have tried the below code
string Result="";
var SF = (from site in db.SF where site.Code == "xyz" select site.Line2).FirstOrDefault(); // Here I ll get "abc"
int Count = (from Ps in db.Ps where Ps.No.StartsWith(SF) select Ps.No).ToList().Count;
if (Count != 0)
{
var PNo = (from Ps in db.Ps where Ps.No.StartsWith(SF) select Ps.No).ToList().LastOrDefault();
if (PNo != null)
{
int Val = Convert.ToInt32(PNo.Replace(SF, "")) + 1; // Here I need to get `abc1000` based on the above ex. list.
Res = SF + Val.ToString();
}
}
else
{
Result = SF + "1";
}
When I execute the code, It always comes with "abc10" after It reached "abc45". Any help in providing the generic logic will be appreciated.
Thanks
Try below code :
var myStrings = new List<string>();
myStrings.Add("abc9");
myStrings.Add("abc100");
myStrings.Add("abc999");
myStrings.Add("abc");
var maxNumber = "abc" + (from myString in myStrings let value = Regex.Match(myString, #"\d+").Value select Convert.ToInt32(value == string.Empty ? "0" : Regex.Match(myString, #"\d+").Value) + 1).Concat(new[] { 0 }).Max();
Use OrderByDescending() to get the biggest number and then add +1 to result
var result = (from Ps in db.Ps
where Ps.No.StartsWith(SF)
select Ps.No)
.OrderByDescending(m => m.PS.No)
.FirstOrDefault();
How about this? I tried it and it seems to do what you are describing.
public static string testString(string[] input, string startString)
{
int max = 0;
try
{
max = input.Where(s => s.StartsWith(startString) && s.Length > startString.Length)
.Max(s => int.Parse(s.Replace(startString, string.Empty)));
}
catch
{
// no worries, this means max was "abc" without a number
}
return string.Format("{0}{1}", startString, (max + 1).ToString());
}
call it with
string test = testString(new string[] { "abc1", "abc123", "abc23", "xyz23" }, "abc");
try the below mentioned code to get the Max number from your List
var max = myList.Select(v => int.Parse(v.Substring(3))).Max();

Categories

Resources