[英]Getting distinct values from a list of objects with objects
我有一个有两个对象的类。 例如:
public class Animal
{
public Carnivorous MeatEater { get; set; }
public Herbivorous VegEater { get; set; }
public Animal()
{
this.MeatEater = new Carnivorous();
this.VegEater = new Herbivorous();
}
}
Carnivorous
和Herbivorous
有一个Category
属性。
我用我的数据库中的数据列表填充了这个类,该数据存储在MeatEater
或VegEater
。 我需要从两者中获得一个明确的Category
列表,并将MeatEater
和VegEater
结合起来。 我怎样才能得到这个清单?
谢谢!
如果我正确地理解了你的问题,那么你去:(这是假设Category
是一个string
,否则你还必须在你的类类中重载Equals
):
var result = myList.SelectMany(GetValidCategories).Where(s => s != null)
.Distinct();
所需功能:
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;
}
但是,这不是一个好的设计。 动物是肉食和/或食用者。 他们没有它们。
一个更好的设计是这样的:
[Flags] public enum AnimalType { Carnivorous = 1, Herbivorous = 2, Ominovorous = 3 }
public class Animal
{
public AnimalType Type { get; set; }
public string Category { get; set; }
//all the other members that Herbivorous + Carnivorous share,
//so pretty much all of them really.
}
然后,它会更容易:
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);
所以最后lstCategories最后会有不同的组合类别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.