簡體   English   中英

在C#中創建一個獨特的自定義類型列表

[英]Creating a distinct list of custom type in C#

我收到一個實體框架類型列表,並希望只返回List中的不同值。 我正在使用以下方法,但它並沒有統一列表。 有什么建議么?

參數: List<Flag> flags

List<Flag> distinctFlags = flags.Distinct().ToList();

Flag的值如下:ID,Flag,FlagValue。 我可以在這個例子中使用linq嗎?

謝謝。

假設Flag是您的實體模型之一,您可以使用partial class並覆蓋EqualsGetHashCode 這也假設您在Flag class上有一個Id屬性,它唯一地標識它。

//this namespace MUST match the namespace of your entity model.
namespace Your.Entity.Model.Namespace
{
    public partial class Flag
    {
        public override bool Equals(object obj)
        {
            var item = obj as Flag;

            if (item == null)
            {
                return false;
            }

            return this.Id.Equals(item.Id);
        }

        public override int GetHashCode()
        {
            return this.Id.GetHashCode();
        }
    }
}

用法看起來像這樣

List<Flag> distinctFlags = allFlags.Distinct().ToList();

可能flags是一個引用類型的列表,而distinct不會像你期望的那樣工作! 這是因為Distinct()不對列表中的標志值起作用,而是對其內存引用(即所有不同的)起作用。

你必須編寫一個比較器類來教授如何比較等標志。 假設你有這個標志類:

public class flag
{ 
    public string Name { get; set; }
    public string Code { get; set; }
}

你應該創建一個這樣的比較器類:

class FlagComparer : IEqualityComparer<flag>
{
    // Products are equal if their names and product numbers are equal.
    public bool Equals(flag x, flag y)
    {

        //Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //Check whether the products' properties are equal.
        return x.Code == y.Code && x.Name == y.Name;
    }
}

並致電你的聲明:

List distinctFlags = flags.Distinct(new FlagComparer ()).ToList();

通過這種方式,Distinct方法確切地知道如何比較equals flag istance。

UPDATE

根據您的評論,如果您想要遵循我的建議,您應該編寫比較基數如下:

class FlagComparer : IEqualityComparer<flag>
    {
        // Products are equal if their names and product numbers are equal.
        public bool Equals(flag x, flag y)
        {

            //Check whether the compared objects reference the same data.
            if (Object.ReferenceEquals(x, y)) return true;

            //Check whether any of the compared objects is null.
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                return false;

            //Check whether the products' properties are equal.
            return x.HostID == y.HostID && x.RuleID == y.RuleID && x.Flag == y.Flag && x.FlagValue == y.FlagValue;
        }
    }

當然,每個屬性都必須是值類型。

看看這里澄清自己:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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