9

I have a Dictionary<string,int> dictionary1 and I need to convert it into a List<Data> where Data has the properties lable = dictionary1.key and value = dictionary1.value. I don't want to use a for/foreach loop (written by myself) because in order to avoid it I am trying to use a Dictionary.

Another option would be having two different dictionaries (dictionary2 and dictionary3) where dictionary2<string,keyOfDictionary1> and dictionary3<string,valueOfDictionary1>.

Do I make sense? Is that possible? Is there a better option?


Uncaught SyntaxError: Unexpected token ILLEGAL?

I am making an AJAX call via jQuery which results in the above mentioned error. The strange part is the code works fine on LAMP, WAMP but when it is ported to a real server its giving the problem.

Here's my AJAX call:

function wordAnalysis() {
    $("#spinner").show();
    removeTopics();
    $.ajax({
            type: "POST",
            url: "{$site_root_path}pages/wordanalysis.php",
            data: "statuses="+json_statuses,
            success: function(msg){
                $("#mainstage").html(msg);
                $("#spinner").hide();
            }
    });
}

Here's the Smarty .tpl file that is loaded from the AJAX call

<script type="text/javascript">{$words}</script>
<script type="text/javascript" src="{$site_root_path}extlib/jQCloud/jqcloud-1.0.0.min.js"></script>
<link rel="stylesheet" type="text/css" href="{$site_root_path}extlib/jQCloud/jqcloud.css" />
<script type="text/javascript">
$(document).ready(function() {
    var max = {$max};
    var avg = {$avg};
    var time_taken = {$time_taken};
    var count = {$count};
    var size;
{literal}
    var text;
    var color;
    var span;
    var ele;
    var word_list = [];
    var table_height = $("#contentTable").height();
    var orig_table_height = 563;
    var ratio = table_height / orig_table_height;
    var max_font_size = 45;
    for (var word in words) {
        if (words[word]['total'] < avg) {
            continue;
        }
        color = Math.floor((words[word]['url']*100)/words[word]['total']);
        size = Math.floor((words[word]['total']/max)*max_font_size);
        size = Math.round(size*ratio);
        var item = new Array();
        item['text'] = word;
        item['weight'] = words[word]['total'];
        var html = new Array();
        if (color <= 10) { html['style']= "color: #68a1ff;"; }
        else if (color <= 20) { html['style']= "color: #4088ff;"; }
        else if (color <= 30) { html['style']= "color: #2477ff;"; }
        else if (color <= 40) { html['style']= "color: #0060ff;"; }
        else if (color <= 50) { html['style']= "color: #0057e6;"; }
        else if (color <= 60) { html['style']= "color: #004ece;"; }
        else if (color <= 70) { html['style']= "color: #0044b5;"; }
        else if (color <= 80) { html['style']= "color: #003996;"; }
        else if (color <= 90) { html['style']= "color: #002c75;"; }
        else { html['style']= "color: #002562;"; }
        html['style'] += " font-size: "+size;
        item['html'] = html;
        word_list.push(item);
    }
    $("#mainstage").jQCloud(word_list);
});
</script>
<style type="text/css">
    #mainstage span.w10, #mainstage span.w9, #mainstage span.w8, #mainstage span.w7 {
        text-shadow: 0px 1px 1px #ccc;
    }
    #mainstage span.w3, #mainstage span.w2, #mainstage span.w1 {
        text-shadow: 0px 1px 1px #fff;
    }
</style>
{/literal}
<link rel="stylesheet" type="text/css" href="{$site_root_path}assets/css/popup.css" />
<script type="text/javascript" src="{$site_root_path}assets/js/popup.js"></script>

What could be the reason for such an error that too only on a real server and not on LAMP, WAMP ? I've basically tested it with chrome.

Edit:

The data is returned as JSON after the call.

$words = StatusProcessing::findWords($statuses, $max, $avg);
$words = 'var words = '.json_encode($words);
$this->addToView('words', $words);

(this addToView is a function that builds upon Smarty's assign function.)

4

9 回答 9

19

假设:

class Data
{
    public string Label { get; set; }

    public int Value { get; set; }
}

然后:

Dictionary<string, int> dic;
List<Data> list = dic.Select(p => new Data { Label = p.Key, Value = p.Value }).ToList();
于 2012-07-13T12:17:59.320 回答
5

也许你可以使用 LINQ?

dictionary1.Select(p => new Data(p.Key, p.Value)).ToList()

然而,这正在使用yield,因此在后台循环......

于 2012-07-13T12:17:22.883 回答
4
myDictionary.Select(x => new Data(){ label = x.Key, value = x.Value).ToList();
于 2012-07-13T12:17:32.863 回答
2

我假设“无循环”实际上意味着“我想要 LINQ”:

List<Data> = dictionary1.Select(
    pair => new Data() {
        label = pair.Key,
        value = pair.Value
    })).ToList();
于 2012-07-13T12:19:21.023 回答
1

尝试

dictionary1.Select(p => new Data(p.Key, p.Value)).ToList();
于 2012-07-13T12:18:16.043 回答
1

.NET 已经有一种数据类型可以做的Data事情:KeyValuePair<T1,T2>. Dictionary 已经实现IEnumerable<KeyValuePair<T1,T2>>,只需转换为它。

Dictionary<string, int> blah = new Dictionary<string, int>();
IEnumerable<KeyValuePair<string, int>> foo = blah;
于 2012-07-13T12:21:48.887 回答
1

这是一个旧帖子,但只是为了帮助其他人;)

转换任何对象类型的示例:

public List<T> Select<T>(string filterParam)
{    
    DataTable dataTable = new DataTable()

    //{... implement filter to fill dataTable }

    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> row;

    foreach (DataRow dr in dataTable.Rows)
    {
        row = new Dictionary<string, object>();
        foreach (DataColumn col in dataTable.Columns)
        {
            row.Add(col.ColumnName, dr[col]);
        }
        rows.Add(row);
    }

    string json = new JavaScriptSerializer().Serialize(rows);

    using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
    {
        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T[]));
        var tick = (T[])deserializer.ReadObject(stream);
        return tick.ToList();
    }
}
于 2015-07-14T14:27:51.847 回答
0
    public class Data
    {
        public string Key { get; set; }

        public int Value { get; set; }
    }

    private static void Main(string[] args)
    {
        Dictionary<string, int> dictionary1 = new Dictionary<string, int>();
        dictionary1.Add("key1", 1);
        dictionary1.Add("key2", 2);

        List<Data> data = dictionary1.Select(z => new Data { Key = z.Key, Value = z.Value }).ToList();

        Console.ReadLine();
    }
于 2012-07-13T12:17:54.337 回答
0

以防万一只是帮助任何人,我这样做了 - 将处理比单个值类型更复杂的对象,如 OP 所述。

// Assumes: Dictionary<string, MyObject> MyDictionary;
List<MyObject> list = new List<MyObject>();
list.AddRange(MyDictionary.Values.ToArray());
于 2017-06-21T23:48:47.647 回答