Click here to Skip to main content
15,903,030 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've got this code:

C#
internal static List<String> GetLocalities()
{
    List<PhotraxBaseData> psets = new List<PhotraxBaseData>();
    using (var db = new SQLite.SQLiteConnection(App.DBPath))
    {
        string sql = "SELECT DISTINCT City FROM PhotraxBaseData ORDER BY City";
        psets = db.Query<PhotraxBaseData>(sql);
    }
    List<String> cityNames = (from a in psets select a.City).ToList();
    return cityNames;
}


...which gives me more-or-less good data, except that I get an Empty String in the list, too. How can I ignore empty strings as "City" values so that they are not added to the cityNames list?
Posted

change your sql statement

string sql = "SELECT DISTINCT City FROM PhotraxBaseData WHERE isnull(City,'') <> '' ORDER BY City";
 
Share this answer
 
C#
using Linq;

// sample test
private List<string> psets = new List<string>
{
    "",
    "London",
    "", 
    null, 
    " ", 
    "\t\t",
    "\n",
    "New York"
};


List<string> cityNames = psets.Where(
    str => 
    ! 
    (String.IsNullOrEmpty(str) 
    || 
    String.IsNullOrWhiteSpace(str)))
    .ToList();

// result => London / New York
 
Share this answer
 
v3
Comments
DamithSL 2-Nov-14 3:20am    
psets.Where(s => ! String.IsNullOrWhiteSpace(s)).ToList()
will do the same
BillWoodruff 2-Nov-14 6:17am    
Thanks, Damith, that's a good point; I don't know where I got in the habit of adding both checks. I've voted your SQL solution +5.

bool s = String.Empty == ""; // ==> true;
This, based >on Bill Woodruff's idea, works for me:

C#
internal static List<String> GetLocalities()
{
    List<PhotraxBaseData> psets = new List<PhotraxBaseData>();
    using (var db = new SQLite.SQLiteConnection(App.DBPath))
    {
        string sql = "SELECT DISTINCT City FROM PhotraxBaseData ORDER BY City";
        psets = db.Query<PhotraxBaseData>(sql);
    }
    List<String> cityNames = (from a in psets select a.City).Where(
        str =>
        !
        (String.IsNullOrEmpty(str)
        ||
        (String.IsNullOrWhiteSpace(str)))).ToList();
    return cityNames;
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900