将列表中的不同项与列表中的第一项进行比较

本文关键字:列表 一项 比较 | 更新日期: 2023-09-27 18:16:04

我有一个GroupSummary class,它有一些像这样的属性:

public class GroupsSummary
{
    public bool UsedRow { get; set; }
    public string GroupTin   { get; set; }
    public string PayToZip_4 { get; set; }
    public string PayToName  { get; set; }
    public string PayToStr1     { get; set; }
    public string PayToStr2     { get; set; }
    public string PayToCity     { get; set; }
    public string PayToState    { get; set; }
    public bool   UrgentCare_YN { get; set; }
}

然后我有一个Dictionary<string, List<GroupSummary>

对于每个这些字典项,我首先获得FIRST项在其列表中的值,我感兴趣的是:

PayToStr1,PayToStr2,PayToCity,PayToState

现在对于该键的列表中的其余项,(所以从第二个项)我想找到所有的组合(只是字符串连接是好的)他们的PayToStr1,PayToStr2,PayToCity,PayToState与我上面选择的第一项不同。

写这个的好方法是什么?我可以做一个for-each loop并解决它,但我希望有一些更好的LINQ方法来做到这一点。

将列表中的不同项与列表中的第一项进行比较

List<GroupsSummary> items = new List<GroupsSummary>();
var first = items.First();
var others = from i in items.Skip(1)
             where i.PayToStr1 != first.PayToStr1 ||
                   i.PayToStr2 != first.PayToStr2 ||
                   ....
             select i;

或者您可以在GroupsSummary中定义一个方法,并在where子句中使用它:

public bool IsDifferentFrom(GroupsSummary other)
{
    return PayToStr1 != other.PayToStr1 ||
           PayToStr2 != other.PayToStr2 ||
           ....;
}
var others = from i in items.Skip(1)
             where i.IsDifferentFrom(first)
             select i;

你可以尝试这样做:

List<GroupSummary> result = dictionary[key].Skip(1)
                                           .Where(x=>(x.PayToStr1+
                                                      x.PayToStr2+
                                                      x.PayToCity+
                                                      x.PayToState)!=
                                                      (dictionary[key][0].PayToStr1+
                                                       dictionary[key][0].PayToStr2+
                                                       dictionary[key][0].PayToCity+
                                                       dictionary[key][0].PayToState))
                                           .ToList();     

你的问题:

查找列表中与列表第一项不同的项。

这是一个简单的整数列表的解决方案:

var items = new List<int> {1, 2, 3, 1, 7, 4, 6, 1, 9};
var query = items
    .Skip(1)
    .Distinct()
    .Where(x => x != items.First())
    .OrderBy(x => x);
foreach (int item in query)
{
    Console.WriteLine(item);
}
预期输出:

2
3
4
6
7
9

很容易扩展这个查询来使用您的GroupsSummary类。只要定义一个实例方法(或者一个扩展方法,如果你不拥有GroupsSummary类)来检查两个GroupsSummary对象的"等价性":

public bool IsEquivalentTo(GroupsSummary other)
{
    return
        this.PayToStr1.Equals(other.PayToStr1) &&
        this.PayToStr2.Equals(other.PayToStr2) &&
        this.PayToCity.Equals(other.PayToCity) &&
        this.PayToState.Equals(other.PayToState);
}

那么上面LINQ查询中的Where约束就变成了:

.Where(x => !x.IsEquivalentTo(items.First())