C# 从包含对象的对象列表中获取不同的值

C# 从包含对象的对象列表中获取不同的值,c#,linq,C#,Linq,我有一个类,其中有两个对象。 例如: public class Animal { public Carnivorous MeatEater { get; set; } public Herbivorous VegEater { get; set; } public Animal() { this.MeatEater = new Carnivorous(); this.VegEater = new Herbivo

我有一个类,其中有两个对象。 例如:

public class Animal
{
    public Carnivorous MeatEater { get; set; }
    public Herbivorous VegEater { get; set; }
    public Animal()
    {           
        this.MeatEater = new Carnivorous();
        this.VegEater = new Herbivorous();
    }
}
肉食性
草食性
具有
类别
属性

我用数据库中的数据列表填充了这个类,这些数据存储在
MeatEater
VegEater
中。 我需要从和
肉食者
素食者
的组合中获得一个不同的
类别
。 我怎样才能得到这份名单


谢谢

如果我正确理解了您的问题,那么您可以这样做:(这是假设
类别
字符串
,否则您还必须在类别类中重载
等于
):

所需的功能:

public static IEnumerable<string> GetValidCategories(Animal a)
{
    List<string> categories = new List<string>();
    if (a.MeatEater != null) categories.Add(a.MeatEater.Category);
    if (a.VegEater != null) categories.Add(a.VegEater.Catergory);
    return categories;
}
那么,就容易多了:

var result = myList.Select(a => a.Category).Where(s => s != null).Distinct();

至少有一种基本方法是首先独立选择它们,然后合并

using System.Linq;

var query1 = (from animal in myList
    select animal.MeatEater.Category).Distinct();

var query2 = (from animal in myList
    select animal.VegEater.Category).Distinct();

var result = query1.Union(query2);

您可以将肉食者的所有类别添加到列表中,如果类别尚未出现,则可以将素食者的所有类别添加到同一列表中

var lstCategories = new List<string>();

foreach(string category in animal.MeatEater.Category)
    if(!lstCategories.Contains(category))
        lstCategories.add(category);

foreach(string category in animal.VegEater.Category)
    if(!lstCategories.Contains(category))
        lstCategories.add(category);
var lstCategories=新列表();
foreach(动物.肉食者.类别中的字符串类别)
如果(!lstCategories.Contains(类别))
添加(类别);
foreach(animal.VegEater.category中的字符串类别)
如果(!lstCategories.Contains(类别))
添加(类别);

因此,最后,这些类别将有一组不同的组合类别

你是如何定义你的
类别的。我认为动物“是”肉食者或素食者,而不是“有”肉食者或素食者。这个组织让我感到难以理解;我希望MeatEater是一个接口。只是为了确保,此列表将只包含0(不存在MeatEater或VegeEater对象)、1(仅分配了MeatEater或VegeEater,或者它们都具有相同的类别),或者此处将返回2个不同的类别,对吗?没有隐藏的信息表明“食肉动物”是一个列表或什么的?对不起,如果我不清楚。对不起,如果我不清楚。根据数据验证,我将其存储在肉食者或素食者中。例如,肉食者有两个记录:“特雷克斯”,一个描述,“非常大”(类别)和“狮子”,一个描述,“中等”。素食者有两个记录:“奶牛”,一个desc,“中等”和“羔羊”,一个desc,“小”。我必须得到一个带有“大”、“中”和“小”的清晰列表。希望我现在明白了。杂食动物想和你谈谈你的假设。:)@Moo Juice
[Flags]
想和你谈谈:PI的意思是,你的台词“动物是肉食者或素食者”。。。“和/或”当然更好。。。因为它们可以都是:)实际上,扩展它。。使用您的
标志
解决方案<代码>枚举动物类型{食肉动物=1,食草动物=2,食草动物=3}
。问题解决了!:)@穆汁再次感谢:)
using System.Linq;

var query1 = (from animal in myList
    select animal.MeatEater.Category).Distinct();

var query2 = (from animal in myList
    select animal.VegEater.Category).Distinct();

var result = query1.Union(query2);
var lstCategories = new List<string>();

foreach(string category in animal.MeatEater.Category)
    if(!lstCategories.Contains(category))
        lstCategories.add(category);

foreach(string category in animal.VegEater.Category)
    if(!lstCategories.Contains(category))
        lstCategories.add(category);