转换<list <list <object>&gt;到<list <list <string>&gt; </list <list <string> </list <list <object>

时间:2014-10-14 09:46:22

标签: c# string list object windows-phone-8.1

我为windows phone 8.1做app,现在我需要将List(List(object))转换为List(List(string))...

    public List<List<string>> ExecuteScalarEx()
    {
        if (_conn.Trace)
        {
            Debug.WriteLine("Executing Query: " + this);
        }

        List<List<object>> result = new List<List<object>>();
        List<List<string>> stringList = new List<List<string>>();

        var stmt = Prepare();

        while (SQLite3.Step(stmt) == SQLite3.Result.Row)
        {
            int columnCount = SQLite3.ColumnCount(stmt);

            List<object> row = new List<object>();
            for (int i = 0; i < columnCount; i++)
            {
                var colType = SQLite3.ColumnType(stmt, i);
                object val = ReadColEx(stmt, i, colType);
                row.Add(val);
            }
            result.Add(row);
        }

        //*** I NEED CONVERT HERE! ****
        //stringList = ....;


        return stringList;
    }

有什么想法吗?提前致谢! :)

2 个答案:

答案 0 :(得分:3)

我认为List.ConvertAll可用,不是吗?

List<List<string>> stringList = result.ConvertAll(
    list => list.ConvertAll(obj => (obj ?? "").ToString()));

在这种情况下(您现在提供了代码),首先应该以{{1​​}}开头。

答案 1 :(得分:1)

你可以用普通的Linq来做,但蒂姆的解决方案更整洁:

using System.Linq;

....

List<List<string>> stringList = result.Select(
    lst => lst.Select(o => (o ?? "").ToString()).ToList()
).ToList()

当然,您可以首先将DB值读作字符串...

public List<List<string>> ExecuteScalarEx()
{
    if (_conn.Trace)
    {
        Debug.WriteLine("Executing Query: " + this);
    }

    List<List<string>> stringList = new List<List<string>>();

    var stmt = Prepare();

    while (SQLite3.Step(stmt) == SQLite3.Result.Row)
    {
        int columnCount = SQLite3.ColumnCount(stmt);

        List<string> row = new List<string>();
        for (int i = 0; i < columnCount; i++)
        {
            var colType = SQLite3.ColumnType(stmt, i);
            string val = (ReadColEx(stmt, i, colType) ?? "").ToString();
            row.Add(val);
        }
        stringList.Add(row);
    }

    return stringList;
}