什么是比较两个列表<custom> </custom>的最佳方法

时间:2014-08-28 23:04:44

标签: c# list compare

class MasterList
{
    public int ID = int.MinValue;
    public DateTime LastUpdated = DateTime.MinValue;

    public MasterList(String sId, String sLastUpdated)
    {
        sId = ("" + sId).Trim();
        sLastUpdated = ("" + sLastUpdated).Trim();
        if (sId != "" && sLastUpdated != "")
        {
            ID = Convert.ToInt32(sId);
            LastUpdated = Convert.ToDateTime(sLastUpdated);
        }
    }
}

List<MasterList> MostUpdatedListFromDataProvider;
List<MasterList> LocalDBList;

如何在两个单独的列表中找到ADD ID和要更新的ID。需要两个单独的列表1.添加新产品2.更新产品。

我试过这个来获取IDsToUpdate。

public static List<int> IDsToUpdate(List<MasterList> DDF, List<MasterList> DB)
    {
        List<int> IDs = new List<int>();

        foreach (MasterList ml in DDF)
        {
            MasterList q = (from dbb in DB
                            where dbb.ID.Equals(ml.ID)
                            where dbb.LastUpdated < ml.LastUpdated
                            select dbb).SingleOrDefault();
            if (q != null)
            {
                Console.WriteLine("IDsToUpdate: " + ml.ID);
                IDs.Add(ml.ID);
            }
        }

        return IDs;
    }

但这太慢了。

1 个答案:

答案 0 :(得分:0)

如果您希望了解MasterListMostUpdatedListFromDataProvider项中不属于LocalDBList的{​​{1}}项,请MasterList实施IEquatable<MasterList>提供类中Equals()方法的相关比较(不要忘记重写GetHashCode()):

class MasterList : IEquatable<MasterList>
{
    public int ID = int.MinValue;
    public DateTime LastUpdated = DateTime.MinValue;

    public MasterList(String sId, String sLastUpdated)
    {
        if (!string.IsNullOrEmpty(sId) && 
            !string.IsNullOrEmpty(sLastUpdated))
        {
            ID = Convert.ToInt32(sID);
            LastUpdated = Convert.ToDateTime(sLastUpdated);      
        }
    }

    public bool Equals(MasterList other)
    {
        return (this.ID == other.ID &&
                this.LastUpdated == other.LastUpdated);
    }

    public override int GetHashCode()
    {
        return this.ID.GetHashCode() * this.LastUpdated.GetHashCode();
    }
}

请注意,这假定sIdsLastUpdated将转换为intDateTime - 您可能希望为此添加进一步的检查。

现在已经到位,您可以使用Enumerable.Except来检索两个Lists之间的差异:

var differences = MostUpdatedListFromDataProvider.Except(LocalDBList);

根据每个List的大小,如果您更换它们,可能会发现不同的性能。

var differences = LocalDBList.Except(MostUpdatedListFromDataProvider);

因为一个List将被完全读入内存而另一个被流式传输,但可能更快的方式不符合您的要求。

相关问题