截断列表<;字符串>;使用Helper方法

本文关键字:使用 Helper 方法 gt 字符串 lt 列表 | 更新日期: 2023-09-27 18:01:11

我正在尝试减少从查询返回的标题的大小。

[WebMethod]
public List<string> LoadNews(string article) {
    var newsList = new List<string>();
    using (var db = new DbDataContext())
    {
        var newsItem = db.News.Where(x => x.NewsTitle.Contains(article));
        newsList.AddRange(newsItem.Select(item => item.NewsTitle));
    }
    return newsList;
}

它正在与jquery UI autocomplete一起使用,以上是数据的来源。我做了一个助手方法来尝试包装return newslist

public string Truncate(string source, int length)
{
    if (source.Length > length)
    {
        source = source.Substring(0, length);
    }
    return source;
}

如何使退货类型匹配?我曾想过在Truncate中放入一个foreach,但无法实现。

截断列表<;字符串>;使用Helper方法

方法如下所示:

public void Truncate(List<string> newsList, int length)
{
    for (int i = 0; i < newsList.Count; i++)
    {
        newsList[i] = newsList[i].Substring(0, length);
    }
}

没有理由返回列表,因为您正在方法中编辑列表。