簡體   English   中英

C#比較不同集合中的屬性值

[英]C# compare values of properies in different collections

我有一些課:

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; }
}

我試圖創建方法找到RegionList<AddressInfoes>等於RegionName在IEnumerable的:

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”不同的含義,“ reg”已在“父或當前”范圍中用於表示其他名稱:C:\\ TEMP \\ ConsoleApplication1 \\ ConsoleApplication1 \\ Program.cs 89 39 MultipartFormData

這應該工作

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

我有這段代碼,也許是過大了,但是很通用:

    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);

region是AddressInfoes ,regions2是Regions

此方法返回bool 當集合相等時->相同大小並且所有項目都根據謂詞匹配,則返回true

bool isEqual = addresses.Select(a=>a.Region).Distinct().OrderBy(x=>x)
              .SequenceEqual(regions.Select(r=>r.RegionName).Distinct().OrderBy(x=>x));

暫無
暫無

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

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