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

C# (Xamarin) fire-and-forget from overridden framework call
c# Navigate through different forms
How to get full access to the variable in another Unity class [duplicate]
How to check csv file type in c# [duplicate]
compilationWin32Exception when building Windows Store App in unity3D
Get Maximum Password Age maxPwdAge from LDAP Active Directory connection in asp.net mvc
LINQ: equivalent for string_agg from PostgreSql
Google maps closes immediately after opening
Update to Azure Notification hub tags fails when tags list is empty
Attempted to read or write protected memory on DAQ
AvalonEdit : Tab Key Handling
Binding error in design and runtime on usercontrol
Handle embedded browser 404 error from external DLL in WPF
How to send keys started hidden CMD process
How do I sort the strings I have in a textfile properly?
An exception of type 'System.Data.SqlClient.SqlException' occurred

Categories

HOME
pact
autohotkey
redux
compression
readdir
livecharts
snmp
aggregation-framework
richtextbox
schema
install
browserstack
revit-api
apache-httpclient-4.x
jpql
google-search-appliance
fetch
xmlhttprequest
comma
yui
aggregate
airbnb
civicrm
tcpdf
inline-assembly
apdu
windowserror
ckeditor4.x
continuous-fourier
adobe-captivate
utc
cloudformation
resx
boosting
ipython-parallel
ocl
folder
blockly
mplab
choco
certbot
sdl-2
gstreamer-1.0
console.readline
form-fields
idea-plugin
google-cloud-powershell
codepen
gradlew
infovis
skype-bots
e4
vertex
fckeditor
liferay-ide
printer-control-language
recursive-query
timefield
mavlink
consolidation
foreground
php-java-bridge
django-celery
opendolphin
recode
mojolicious
sdkman
self-join
tooltwist
callfire
xmla
alpha-beta-pruning
tigase
azure-worker-roles
isl
farpoint-spread
email-headers
mixradio
nomachine
vbaccelerator
autofilter
netbeans-plugins
xcode6.1-gm-seed
lastinsertid
jfilechooser
surfaceview
dynamic-expresso
bho
generator-expression
motordriver
jquery-ui-map
symfony-1.2
xhtmlrenderer
netduino
n2
rollover
xslt-grouping
system-analysis
focus-stealing
atmega16
memory-consumption

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