簡體   English   中英

從具有對象的對象列表中獲取不同的值

[英]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();
    }
}

CarnivorousHerbivorous有一個Category屬性。

我用我的數據庫中的數據列表填充了這個類,該數據存儲在MeatEaterVegEater 我需要從兩者中獲得一個明確的Category列表,並將MeatEaterVegEater結合起來。 我怎樣才能得到這個清單?

謝謝!

如果我正確地理解了你的問題,那么你去:(這是假設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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM