您好我有一个列表列表哪个是动态的,有时候我的列表包含两个列表,或者有时候它会包含三个列表,就像这里我们可以说我的列表包含三个列表。
list1.Add(new Schema() { High = 10, Low = 8, OpenValue = 7, Price = 8.5, Time = DateTime.Today.AddDays(-7), Volume = 234234232 });
list2.Add(new Schema() { High = 10, Low = 8, OpenValue = 7, Price = 8.5, Time = DateTime.Today.AddDays(-6), Volume = 234234232 });
list3.Add(new Schema() { High = 10, Low = 8, OpenValue = 7, Price = 8.5, Time = DateTime.Today.AddDays(-7), Volume = 234234232 });
我有
List<List<Schema>> llsl = new List<List<Schema>>();
llsl.Add(list1);
llsl.Add(list2);
llsl.Add(list3);
现在我想要比较列表,首先我必须比较list1 to list2
然后list1 to list3
然后list2 to list3
然后list2 to list1
等等所以任何人都可以帮助我我怎么能得到它。
这样做的目的我希望最终列表哪个包含相同的no项目让我们说我的list1包含日期20 feb同样我的list3也包含一个日期20feb但我的list2不包含所以我想要包含所有三个列表的最终列表但是list2具有空值,因为它不包含20个feb所以基本上我想要比较列表中的日期。
先谢谢。
答案 0 :(得分:0)
你的问题对我来说并不是很清楚,但如果你想让元素为null,如果它与集合中的任何其他元素都不匹配,那么你就是这样。
覆盖名为Schema的类中的Equals和Hash方法,如下所示:
public class Schema
{
public int High { get; set; }
public int Low { get; set; }
public int OpenValue { get; set; }
public double Price { get; set; }
public DateTime Time { get; set; }
public int Volume { get; set; }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Schema)obj);
}
protected bool Equals(Schema other)
{
//You may would like to compare only Date here.
return High == other.High && Low == other.Low && OpenValue == other.OpenValue && Price.Equals(other.Price) && Time.Equals(other.Time) && Volume == other.Volume;
}
public override int GetHashCode()
{
unchecked
{
int hashCode = High;
hashCode = (hashCode * 397) ^ Low;
hashCode = (hashCode * 397) ^ OpenValue;
hashCode = (hashCode * 397) ^ Price.GetHashCode();
hashCode = (hashCode * 397) ^ Time.GetHashCode();
hashCode = (hashCode * 397) ^ Volume;
return hashCode;
}
}
}
然后创建如下的扩展方法。(查看逻辑的注释)。
public static class ListExtension
{
public static List<List<T>> MatchList<T>(this List<List<T>> list) where T : class
{
//will contain matched list element index
var matchedList = new List<Tuple<int, int>>();
for (var i = 0; i < list.Count - 1; i++)
{
for (var j = i + 1; j < list.Count; j++)
{
//add element to matchedList if all are equal.
var iElement = list.ElementAt(i);
var jElement = list.ElementAt(j);
if (iElement.Count != jElement.Count) continue;
var flag = !iElement.Where((t, k) => !iElement.ElementAt(k).Equals(jElement.ElementAt(k))).Any();
if (flag)
{
//add element here.
matchedList.Add(new Tuple<int, int>(i, j));
}
}
}
var item1 = matchedList.Select(d => d.Item1).ToList();
var item2 = matchedList.Select(d => d.Item2).ToList();
//distinct elements that matchced perfectly.
var sameGroup = item1.Union(item2);
for (var i = 0; i < list.Count; i++)
{
if (!sameGroup.Contains(i))
{
//make it null where it did not matched as your requirement
list[i] = null;
}
}
//finally return the updated list.
return list;
}
}
Here正在帮助你,以防你想测试和玩它。