【问题标题】:C# compare values of properies in different collectionsC#比较不同集合中的属性值
【发布时间】:2013-08-20 09:21:48
【问题描述】:

我有一些课:

public class AddressInfoes
{
    public int Id { get; set; }
    public string Region { get; set; }
    public int RegionID { get; set; }
}

和类:

public class Regions
{
    public int Id { get; set; }
    public string RegionName { get; set; }
    public int RegionID { get; set; }
}

我正在尝试在 IEnumerable 中创建查找 List<AddressInfoes>Region 等于 RegionName 的方法:

private bool RegionCheck(List<AddressInfoes> addresses, IEnumerable<Regions> regions)
{
    return regions.Any(x=>addresses.Any()y=>y.Region.Equals(x.RegionName));
}

但是这种方法不能正常工作? 我该如何实施?

我需要通过两个属性进行比较:

  var result = addresses.Where(reg => !regions.Any(y => y.RegionName.Equals(reg.Region.Trim(), StringComparison.InvariantCultureIgnoreCase))
            && addresses.Where(reg => !regions.Any(y => y.RegionDomainID == reg.RegionDomainID)));

但我有错误:

错误 1 ​​不能在此范围内声明名为“reg”的局部变量,因为它会给“reg”赋予不同的含义,后者已在“父或当前”范围中用于表示其他内容 C:\TEMP \ConsoleApplication1\ConsoleApplication1\Program.cs 89 39 MultipartFormData

【问题讨论】:

  • 您是要查找地区还是有地区?

标签: c# linq list compare


【解决方案1】:

这应该可以工作

regions.Where(x => addresses.Any(addr => addr.Region == x.RegionName));
//.ToList() or .Any();

【讨论】:

  • @user2469940 - 要么将.Any() 放在末尾,要么将Where 更改为Any
【解决方案2】:
bool isEqual = addresses.Select(a=>a.Region).Distinct().OrderBy(x=>x)
              .SequenceEqual(regions.Select(r=>r.RegionName).Distinct().OrderBy(x=>x));

【讨论】:

    【解决方案3】:

    我有这段代码,也许它有点过头了,但它是通用的:

        public static bool IsEquivalent<T, TU>(this ICollection<T> collection, ICollection<TU> sourceCollection, Func<T, TU, bool> predicate) where T : class
        {
            var copyCollection = collection.Clone();
    
            if (copyCollection.Count == 0 && !sourceCollection.Any()) return true;
            foreach (var source in sourceCollection)
            {
                var element = copyCollection.FirstOrDefault(x => predicate(x, source));
                if (element == null) return false;
                copyCollection.Remove(element);
            }
            return !copyCollection.Any();
        }
    
        public static ICollection<T> Clone<T>(this ICollection<T> listToClone)
        {
            var array = new T[listToClone.Count];
            listToClone.CopyTo(array, 0);
            return array.ToList();
        }
    

    你可以这样称呼它:

    regions.IsEquivalent(regions2, (x,y)=>x.Region==y.RegionName);
    

    区域为AddressInfoes,区域2 为Regions

    此方法返回bool。当集合等价 -> 大小相同且所有项目根据谓词匹配时,它会返回 true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 2023-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      相关资源
      最近更新 更多