c#


Shift elements in string array to left to fill 'holes'


I have a list of names and phone numbers like so:
var phonelist = List<string[]>
{
new string[] {"Bill", "1234", "12345", "12314" },
new string[] {"Bob", "", "12345", "12314" },
new string[] {"Chris", "", "", "12314" },
new string[] {"Dave", "1234", "", "12314" },
new string[] {"Andy", "1234", "12345", "" },
}
What is the most efficient/elegant way to process this list so that the 'empty' numbers get filled from the right ?
Note, the arrays should stay the same length, like so:
var phonelist = List<string[]>
{
new string[] {"Bill", "1234", "12345", "12314" },
new string[] {"Bob", "12345", "12314", "" },
new string[] {"Chris", "12314", "", "" },
new string[] {"Dave", "1234", "12314", "" },
new string[] {"Andy", "1234", "12345", "" },
}
for each array cell, check if its empty and swap it with cell+1, if it's still empty swap it with cell+2.. when cell becomes not empty do the same thing with cell+2...
int j;
foreach (string[] strs in phoneList)
{
for (int i = 0; i < strs.Length; i++)
{
j = 1;
while (string.IsNullOrEmpty(strs[i]) && j < strs.Length - i)
{
if (!string.IsNullOrEmpty(strs[i + j])) // to not swap 2 empty strings
{
strs[i] = strs[i + j];
strs[i + j] = "";
}
j++;
}
}
}
public static void PutEmptyStringsToTheEnd(string[] array) {
int j = 0;
for (int i = 0; i < array.Length; ++i)
if (array[i].Length > 0)
array[j++] = array[i];
while (j < array.Length)
array[j++] = "";
}
Call this function for each List element.
simple and ugly :(
for(var x=0;x<phonelist.Count;x++)
{
var strings = phonelist[x];
var l = strings.Length;
var newAr=new string[l];
var k = 0;
for (var i = 0; i < l; )
{
if(strings[i]!="")
{
newAr[k++] = strings[i];
}
i++;
}
for (; k < l; k++)
newAr[k] = "";
phonelist[x] = newAr;
}
You could do something like that :
Comparison<string> comparison = (x,y) =>
{
if (String.IsNullOrEmpty(x))
return 1;
if (String.IsNullOrEmpty(y))
return -1;
return String.Compare(x,y);
}
foreach (string[] array in phoneList)
{
Array.Sort(array, comparison);
}
However you will need to tune the comparison logic a bit to keep the names before the numbers
EDIT : since the name seems to always be the first element, another option is to exclude it from the sort. No Array.Sort overload takes a Comparison<T> and a range, so you have to use a IComparer<T> instead :
class MyComparer : IComparer<string>
{
public int Compare(string x, string y)
{
if (String.IsNullOrEmpty(x))
return 1;
if (String.IsNullOrEmpty(y))
return -1;
return String.Compare(x,y);
}
}
foreach (string[] array in phonelist)
{
Array.Sort(array, 1, array.Length - 1, new MyComparer());
}
This should work. I'm not that knownledged at C#, but the idea is there
foreach(string[] person in phonelist)
{
string[] newPerson = {"","","",""};
int index = 0;
for(int i=0; i<4; i++)
{
if(!String.IsNullOrEmpty(person[i])) newPerson[index++] = person[i];
}
person = newPerson;
}
This is cooler
List<string[]> result = phonelist.Select(per => per.OrderBy(txt=>txt.Length==0).ToArray()).ToList();
List<string[]> sorted = new List<string[]>();
foreach (string[] entry in phoneList)
{
List<string> nonEmpty = (from s in entry
where String.IsNullOrEmpty(s) == false
select s).ToList();
int pad = entry.Length - nonEmpty.Count;
List<string> pads = new List<string>();
while (pad > 0)
{
pads.Add(String.Empty);
--pad;
}
List<string> sortedEntry = new List<string>();
sortedEntry.AddRange(nonEmpty);
sortedEntry.AddRange(pads);
sorted.Add(sortedEntry.ToArray());
}

Related Links

Load arraylist into a TextBox
Hook a custom function for label's click event
VS2010 Project doesnt build but doesnt show any errors or warnings
Locating ASP Sitemap tree structures child nodes using Selenium webdriver
Post Array as JSON to MVC Controller
Wpf toggle button content on click
Kinect Not Showing Color Image
Print db content into multiple textboxes without using dataset
Solving a postfix notation expression in c#
Serialize Lucene.net Document
Pros/Cons of Stream[Reader/Writer]
Thread safe public string
DataTable.Select as DataSource of DataList
Moq multi interfaces
c# interact html maybe php and javascript with wpf applications
Want to Transmit a live feed from Cellphone to Custom Application over bluetooth

Categories

HOME
airflow
repository
intellij-idea
postgresql-9.3
formatting
casting
gap-system
conceptual
hiveql
opc-ua
browser-cache
schema
yacc
ionic-native
token
soap-client
ndepend
element
yui
sha1
dat.gui
owncloud
internet-explorer-7
beacon
apdu
grunt-contrib-uglify
pydub
smart-device
federated
ipython-parallel
deferred
opencsv
language-detection
oracle-nosql
sdl-2
device-driver
console.readline
redhat-brms
ssdp
datagridviewcombobox
paperclip
peerjs
firefox-developer-edition
amazon-fire-tv
togglebutton
automapper-4
google-cloud-shell
standard-error
playframework-2.3
ajv
r-commander
blitz3d
mongodb-3.3
jira-agile
android-xmlpullparser
avi
sbt-proguard
pebble-js
android-progressbar
angular-promise
transport
self-join
pushwoosh
eaaccessory
grails-3.0.9
data-representation
dockerpy
attiny
javadb
selenium-grid2
sat4j
nspopupbutton
behance-api
codio
tlbimp
nokogiri
violation
wpd
reference-manual
metapost
motordriver
django-1.4
optimistic-concurrency
wxperl
session-hijacking
windows-xp-embedded
functional-specifications
netbeans7.0
llblgen
lgpl
conditional-operator
chromebug
code-golf
glassfish-embedded
time-management
script-tag

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App