从linq列表中选择数组

时间:2014-04-08 06:39:19

标签: c# arrays asp.net-mvc linq

从linQ列表中选择数组时遇到问题。

通常用于某些静态数据的数组 -

  List<string> nameList = new List<string>
            {
                "Jonathan", "Lisa", "Jordan", "Tyler", "Susan", "Brandon", "Clayton", "Elizabeth", "Jennifer"
            };

            var results = nameList.Where(n =>
                n.StartsWith(term, StringComparison.OrdinalIgnoreCase));

            return new JsonResult()
            {
                Data = results.ToArray(),
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

Linq查询 -

var names = (from u in db.Contacts
                         select u).ToList();

现在从上面的linq查询中,此列中将有names。我想通过创建其名称数组从上面的查询中选择名称。如何在此查询中为names设置数组,就像基于静态的数据一样。

修改 -

  [HttpGet]
        public JsonResult GetNames(string term)
        {
            var names = (from u in db.Contacts
                         where u.name.Contains(term)
                         select u).ToArray();
            // A list of names to mimic results from a database

            var results = names.Where(n =>
                n.name.StartsWith(term, StringComparison.OrdinalIgnoreCase));

            return new JsonResult()
            {
                Data = results.ToArray(),
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

我已经从上面修改了这个方法,现在我可以在服务器端获取列表。但是在json结果它留给我internal server error (500)

脚本 -

<script type="text/javascript">
    $(function () {
        $('#typeahead').typeahead({
            source: function (term, process) {
                var url = '@Url.Content("~/Invoice/GetNames")';

                return $.getJSON(url, { term: term }, function (data) {
                    alert(data);
                    return process(data);
                });
            }
        });
    })
</script>

2 个答案:

答案 0 :(得分:2)

简单地说:

var names = (from u in db.Contacts
            select new { Name = u.Name}).ToArray();

答案 1 :(得分:0)

尝试

var names = db.Contacts.Select(x => x.PROP_NAME).ToArray();