split a number into an array of strings - c#

There is a list of candidates.
candid: {12,14,16,19,25,64,78}
Code :
for (int i = 0; i < candid.Count; i++)
{
var searchTerm = candid[i].ToString();
var searchItems = searchTerm.ToCharArray().ToString();
foreach (Tran b in transactions)
{
string[] temp = new string[b.itemsUtilities.Count];
int j = 0;
foreach (ItemUtility c in b.itemsUtilities)
{
temp[j] = c.item.ToString();
j = j + 1;
}
if (searchItems.All(a => temp.Contains(a)))
arraye[i] = arraye[i] + (b.transactionUtility);
}
}
I receive the following error:
'string[]' does not contain a definition for 'Contains' and the best
extension method overload 'Queryable.Contains(IQueryable,
char)' requires a receiver of type 'IQueryable'
If code changed from : var searchItems = searchTerm.ToCharArray().ToString();
To : var searchItems = searchTerm.split();
This error is fixed, But this split command does not separate numbers.

I guess you want to separate the numbers into a string[].
var searchItems = searchTerm.ToCharArray().ToString();
This will always create a single string "System.Char[]" so is not what you want.
I guess you want:
string[] searchItems = searchTerm.Select(c => c.ToString()).ToArray();
This should fix the compiler error because searchItems.All will now project strings and not chars.

More that a simple missing include, I do think that you are over thinking
your code seems to be simplify as :
for (int i = 0; i < candid.Count; i++)
{
var searchTerm = candid[i].ToString();
foreach (Tran b in transactions)
{
var tmp = b.itemsUtilities.Select(x=> x.item.ToString()).ToList();
if( searchTerm.All(a=> tmp.Contains (a)){
arraye[i] = arraye[i] + (b.transactionUtility);
}
}
}
And you can simplify again instead of for each you filter Trasanction based on the if condition.
And if your candid is 11 no need to check twice for 1 so a simple Distinct() will help here.

Related

How can I split a string to store contents in two different arrays in c#?

The string I want to split is an array of strings.
the array contains strings like:
G1,Active
G2,Inactive
G3,Inactive
.
.
G24,Active
Now I want to store the G's in an array, and Active or Inactive in a different array. So far I have tried this which has successfully store all the G's part but I have lost the other part. I used Split fucntion but did not work so I have tried this.
int i = 0;
for(i = 0; i <= grids.Length; i++)
{
string temp = grids[i];
temp = temp.Replace(",", " ");
if (temp.Contains(' '))
{
int index = temp.IndexOf(' ');
grids[i] = temp.Substring(0, index);
}
//System.Console.WriteLine(temp);
}
Please help me how to achieve this goal. I am new to C#.
If I understand the problem correctly - we have an array of strings Eg:
arrayOfStrings[24] =
{
"G1,Active",
"G2,Inactive",
"G3,Active",
...
"G24,Active"
}
Now we want to split each item and store the g part in one array and the status into another.
Working with arrays the solution is to - traverse the arrayOfStrings.
Per each item in the arrayOfStrings we split it by ',' separator.
The Split operation will return another array of two elements the g part and the status - which will be stored respectively into distinct arrays (gArray and statusArray) for later retrieval. Those arrays will have a 1-to-1 relation.
Here is my implementation:
static string[] LoadArray()
{
return new string[]
{
"G1,Active",
"G2,Inactive",
"G3,Active",
"G4,Active",
"G5,Active",
"G6,Inactive",
"G7,Active",
"G8,Active",
"G9,Active",
"G10,Active",
"G11,Inactive",
"G12,Active",
"G13,Active",
"G14,Inactive",
"G15,Active",
"G16,Inactive",
"G17,Active",
"G18,Active",
"G19,Inactive",
"G20,Active",
"G21,Inactive",
"G22,Active",
"G23,Inactive",
"G24,Active"
};
}
static void Main(string[] args)
{
string[] myarrayOfStrings = LoadArray();
string[] gArray = new string[24];
string[] statusArray = new string[24];
int index = 0;
foreach (var item in myarrayOfStrings)
{
var arraySplit = item.Split(',');
gArray[index] = arraySplit[0];
statusArray[index] = arraySplit[1];
index++;
}
for (int i = 0; i < gArray.Length; i++)
{
Console.WriteLine("{0} has status : {1}", gArray[i] , statusArray[i]);
}
Console.ReadLine();
}
seems like you have a list of Gxx,Active my recomendation is first of all you split the string based on the space, which will give you the array previoulsy mentioned doing the next:
string text = "G1,Active G2,Inactive G3,Inactive G24,Active";
string[] splitedGItems = text.Split(" ");
So, now you have an array, and I strongly recommend you to use an object/Tuple/Dictionary depends of what suits you more in the entire scenario. for now i will use Dictionary as it seems to be key-value
Dictionary<string, string> GxListActiveInactive = new Dictionary<string, string>();
foreach(var singleGItems in splitedGItems)
{
string[] definition = singleGItems.Split(",");
GxListActiveInactive.Add(definition[0], definition[1]);
}
What im achiving in this code is create a collection which is key-value, now you have to search the G24 manually doing the next
string G24Value = GxListActiveInactive.FirstOrDefault(a => a.Key == "G24").Value;
just do it :
var splitedArray = YourStringArray.ToDictionary(x=>x.Split(',')[0],x=>x.Split(',')[1]);
var gArray = splitedArray.Keys;
var activeInactiveArray = splitedArray.Values;
I hope it will be useful
You can divide the string using Split; the first part should be the G's, while the second part will be "Active" or "Inactive".
int i;
string[] temp, activity = new string[grids.Length];
for(i = 0; i <= grids.Length; i++)
{
temp = grids[i].Split(',');
grids[i] = temp[0];
activity[i] = temp[1];
}

Convert Array List to Comma Separated String in C#

I'm using String.Join to attempt to turn an array list into a string that is comma separated, such as
xxx#xxx.com,yyy#xxx.com,zzz#xxx.com,www#xxx.com
I can't seem to get the syntax working.
Here's what I'm trying:
for (i = 0; i < xxx; i++)
{
MailingList = arrayList[i].ToString();
MailingList = string.Join(", ", MailingList.ToString());
Response.Write(MailingList.ToString());
}
Can you help me?
Thank you in advance-
Guessing from the name of your variable (arrayList), you've got List<string[]> or an equivalent type there.
The issue here is that you're calling ToString() on the array.
Try this instead:
for (i = 0; i < xxx; i++)
{
var array = arrayList[i];
MailingList = string.Join(", ", array);
Response.Write(MailingList);
}
EDIT: If arrayList is simply an ArrayList containing strings, you can just do
Response.Write(string.Join(", ", arrayList.OfType<string>()));
Personally I would avoid using nongeneric collections (such as ArrayList) if possible and use strongly-typed collections from System.Collections.Generic such as List<string>. For example, if you have a piece of code that depends on that all contents of the ArrayList are strings, it will suffer catastrophically if you accidentally add an item that's not a string.
EDIT 2: If your ArrayList actually contains System.Web.UI.WebControls.ListItems like you mentioned in your comment: arrayList.AddRange(ListBox.Items);, then you'll need to use this instead:
Response.Write(string.Join(", ", arrayList.OfType<ListItem>()));
The second parameter for String.Join needs to be an IEnumerable. Replace MailingList.ToString() with arrayList and it should work.
Initialization:
string result = string.Empty;
For value types:
if (arrayList != null) {
foreach(var entry in arrayList){
result += entry + ',';
}
}
For reference types:
if (arrayList != null) {
foreach(var entry in arrayList){
if(entry != null)
result += entry + ',';
}
}
And cleanup:
if(result == string.Empty)
result = null;
else
result = result.Substring(0, result.Length - 1);
most of the answers are already there, still posting a complete - working snippet
string[] emailListOne = { "xxx#xxx.com", "yyy#xxx.com", "zzz#xxx.com", "www#xxx.com" };
string[] emailListTwo = { "xxx#xxx1.com", "yyy#xxx1.com", "zzz#xxx1.com", "www#xxx1.com" };
string[] emailListThree = { "xxx#xxx2.com", "yyy#xxx2.com", "zzz#xxx2.com", "www#xxx.com" };
string[] emailListFour = { "xxx#xxx3.com", "yyy#xxx3.com", "zzz#xxx3.com", "www#xxx3.com" };
List<string[]> emailArrayList = new List<string[]>();
emailArrayList.Add(emailListOne);
emailArrayList.Add(emailListTwo);
emailArrayList.Add(emailListThree);
emailArrayList.Add(emailListFour);
StringBuilder csvList = new StringBuilder();
int i = 0;
foreach (var list in emailArrayList)
{
csvList.Append(string.Join(",", list));
if(i < emailArrayList.Count - 1)
csvList.Append(",");
i++;
}
Response.Write(csvList.ToString());

Why the checking condition in the inner loop never true?

for (int i = 0; i < ExtractLinks.FilteredLinks.Count; i++)
{
for (int x = 0; x < lockedLinks.Count; x++)
{
if (ExtractLinks.FilteredLinks[i].Contains(lockedLinks[x]))
{
string h = "found";
}
}
}
I want to check if the same link exist in both Lists.
FilteredLinks and lockedLinks both type List
I used a break point and in the FilteredLink i saw this link for example:
http://rotter.net/forum/scoops1/112341.shtml
And in lockedLinks this link:
http://rotter.net/cgi-bin/forum/dcboard.cgi?az=read_count&om=112341&forum=scoops1
Both links lead to the same page. So that's mean both are the same.
So in this case it should stop in the break point i added on : string h = "found";
But since it's never stop there i guess something is wrong with my IF condition.
In case it was found i want to remove the link from the FilteredLinks and also from the lockedLinks to remove what suppose to be the same links from both lists. The links are not identical in the address but they are leading to same page so i consider them as the same/identical and they both should be removed.
If you know the uri format then you can extract the id from the different uri types and compare those:
private static string GetArticleIdFiltered(string filtered)
{
var uri = new Uri(filtered);
return Path.GetFileNameWithoutExtension(uri.LocalPath);
}
private static string GetArticleIdLocked(string locked)
{
var uri = new Uri(locked);
var queryParams = HttpUtility.ParseQueryString(uri.Query);
return queryParams["om"];
}
for (int x = 0; x < lockedLinks.Count; x++)
{
var lockedArticle = GetArticleIdLocked(lockedLinks[x]);
var filteredId = GetArticleIdFiltered(ExtractLinks.FilteredLinks[i]);
if (lockedArticle == filteredId)
{
string h = "found";
}
}
If you know the id is always numeric you can parse it more accurately and compare ints instead of strings.

Foreach loop to check the empty string and assign it a value c#

I dont much idea about Foreach Loop
I have 4 String Variables and i am storing the encrypted values from app.config in those varialbles.My Work is to Detect if there is data in those 4 variables.Even if one doesnt have values i want to pass a default encrypted values to it.I started doing like this......
string EncValue = oEncrypt.EncryptBase64String("NO Data Found");
UpdateOrCreateAppSetting("UserName", ref MPScmUserName);
UpdateOrCreateAppSetting("Password", ref MPScmPassword);
UpdateOrCreateAppSetting("DBUserName", ref MPDbUserName);
UpdateOrCreateAppSetting("DBPassword", ref MPDbPassword);
var list5 = from docs in doc1.Descendants("appender").Elements()
where docs.Name == "file"
select docs;
var element5 = list5.FirstOrDefault();
MPLoadAppConfig = appConfigFile1;
MPErrorLog = element5.Attribute("value").Value;
string[] namesArray = new string[] {
MPScmUserName,MPScmPassword,MPDbUserName,MPDbPassword};
foreach (string i in namesArray)
{
if (i is string)
{
if (i == "")
{
i = EncValue.ToString();
}
}
}
How should i assign default encrypted value to the strings in that array which is a empty string. Please Help me....
You don't need to say if (i is string) because it's already a string.
In another if block you may say
if(string.IsNullOrEmpty(i))
{
}
or you may use:
string[] arr = new string[] { "","A"};
for (int i = 0; i < arr.Length; i++)
{
if (string.IsNullOrEmpty(arr[i]))
{
arr[i] = "Hello";
}
}
Looping on the string array and changing the value of current string doesn't means you are changing the value of the string inside the array. When foreach loops on your array it returns a new string instance in i, so changing that i don't change the value in namesArray.
You need a traditional for loop with an indexer to access directly to the namesArray
for(int i = 0; i < namesArray.Length; i++)
{
if (namesArray[i] == string.Empty)
{
namesArray[i] = EncValue.ToString();
}
}
No need for the if (i is string) part because you already know it's a string. You should probably also use string.IsNullOrWhiteSpace(); to test for an empty string.
Edit (shameless copy from Mark's answer):
for (int i = 0; i < namesArray.Length; ++i)
{
if (string.IsNullOrWhiteSpace(namesArray[i]))
{
namesArray[i] = EncValue.ToString();
}
}
You can't modify the variable in a foreach loop. Your code should give you the following compile error:
Cannot assign to 'i' because it is a 'foreach iteration variable'
You could do this using LINQ:
namesArray = namesArray.Select(s => s == "" ? EncValue.ToString() : s).ToArray();
Alternatively you could use a simple for loop:
for (int i = 0; i < namesArray.Length; ++i)
{
if (namesArray[i] == "")
{
namesArray[i] = EncValue.ToString();
}
}
string[] newNamesArray =
Enumerable.Select(namesArray, s => s == "" ? EncValue : s).ToArray();

When searching for an item in a generic list should I use LINQ or Contains?

I have a generic List and I have to find a particular string in this list. Could you please let me know which is the best approach in the below?
if (strlist.Contains("Test"))
{
// String found
}
or
string res = (from d in strlist where d == "Test" select d).SingleOrDefault();
if (res == "Test")
{
//found
}
Please consider the list may be very big populated from database. Your thoughts on this are highly appreciated.
If you have List<string> (or even IEnumerable<string>) and Contains meets your needs, then use Contains.
If you need some extra handling that Contains doesn't provide, I would suggest using Any():
if(strList.Any(s => s.StartsWith("Tes"))
{
// Found
}
The two methods will behave differently if there is more than one match; the first one will return true and the second one will throw an exception.
To correct that, change SingleOrDefault to FirstOrDefault.
To answer the question, you should call Contains if you're searching for an exact match and Any if you aren't.
For example:
if (strings.Contains("SomeString", StringComparer.OrdinalIgnoreCase))
if (strings.Any(s => s.StartsWith("b"))
You really should use HashSet<string> as the the performance of Contains is dramatically better. Now if you need to use a list for other operations you can simply have both available.
var list = BuildListOfStrings();
var set = new HashSet<string>(list);
if (set.Contains("Test"))
{
// ...
}
Now you have the ability to find items in the set as a O(1) operation.
Test
static void Main(string[] args)
{
var lst = GenerateStrings().Take(5000000).ToList();
var hsh = new HashSet<string>(lst);
var found = false;
var count = 100;
var sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
hsh = new HashSet<string>(lst);
}
Console.WriteLine(TimeSpan.FromTicks(sw.ElapsedTicks / count));
sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
found = lst.Contains("12345678");
}
Console.WriteLine(TimeSpan.FromTicks(sw.ElapsedTicks / count));
sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
found = hsh.Contains("12345678");
}
Console.WriteLine(TimeSpan.FromTicks(sw.ElapsedTicks / count));
Console.WriteLine(found);
Console.ReadLine();
}
private static IEnumerable<string> GenerateStrings()
{
var rnd = new Random();
while (true)
{
yield return rnd.Next().ToString();
}
}
Result
0.308438 s
0.0197868 s
0.0 s
So what does this tell us? If you are making a small amount of calls to Contains use a List<string>, otherwise use a HashSet<string>.

Categories