从对象列表中选择匹配的ID

时间:2016-12-09 15:23:41

标签: c# linq

好的,我有一个列表,其中包含具有以下属性的对象:

category_id category_title

在代码中它看起来像这样:

class CategoryModel
{
    public int category_id { get; private set; }
    public string category_title { get; private set; }

    //Constructor
    public CategoryModel(int id, string title)
    {
        category_id = id;
        category_title = title;
    }

我有这个类的多个对象存储在列表中

    static List<CategoryModel> CategoryList = new List<CategoryModel>();

从此列表中,我尝试选择与 category_id

匹配的 category_title
    public static string GetCategoryName(int categoryNumber)
    {
        IEnumerable<string> title = from c in CategoryList
                    where c.category_id.Equals(categoryNumber)
                    select c.category_title;
        return title.ToString();
    }

让我们说GetCategoryName(4),它现在应该从列表中选择 category_id 等于4并返回 category_title

然而,似乎我没有得到该名称,而是查询的语法!

输出: system.linq.enumerable.whereselectlistiterator'2 [project.CategoryModel,System.string]

6 个答案:

答案 0 :(得分:3)

只需使用Linq即可:

return CategoryList.Single(c => c.category_id == categoryNumber).category_title;
如果类别列表没有任何匹配的ID,

Single将抛出异常。

答案 1 :(得分:1)

您的查询返回的列表不是单个类别。

请试试这个

public static string GetCategoryName(int categoryNumber)
{
    IEnumerable<string> title = from c in CategoryList
                where c.category_id.Equals(categoryNumber)
                select c.category_title;
    return title.FirstOrDefault();
}

答案 2 :(得分:1)

IEnumerable类在ToString函数中没有实现其元素的某种奇特格式。我认为最简单的方法是使用String.Join函数,如果应该有多个结果:

return String.Join(",", title);

答案 3 :(得分:1)

您应该使用Linq选择第一个或默认值:

public static string GetCategoryName(int categoryNumber) {
    return CategoryList.FirstOrDefault( category => category.category_id == categoryNumber).category_title;
}

但是由于.category_title没有这样的类别ID,这会抛出异常,所以最好的解决方案是:

public static string GetCategoryName(int categoryNumber) {
    CategoryModel category = CategoryList.FirstOrDefault( category => category.category_id == categoryNumber);
    return category == null ? string.Empty : category.category_title;
}

当没有找到这样的类别时,将返回空字符串。

关于你回来的错误。这是因为您的查询返回CategoryModel的“很多”对象,即。 IEnumerable<string>然后您尝试转换为字符串。

在任何类型的表(数组,列表等)上执行ToString()都会返回类似system.string[]的内容,或者换句话说,与调用IEnumerable<string> .ToString()的结果相同。

答案 4 :(得分:0)

public static string GetCategoryName(int categoryNumber)
{
    CategoryModel result = CategoryList.Where(x => x.category_id == categoryNumber).FirstOrDefault();
    if (result != null)
        return result.category_name;
    else
        //no matches, do something else
}

这将从CategoryList中获取category_id与您传入的数字相匹配的项目,如果匹配则返回category_name。

答案 5 :(得分:0)

您要对尚未评估的Enumerable进行ToString,这就是您获取查询实现对象的原因。

假设您在匹配的唯一项目之后,请执行:

title.SingleOrDefault()?.ToString()

注意:?运算符仅适用于C#6;你可以进行正常的作业和if x == null类型检查以下

相关问题