C#LINQ方法确定数组是否为另一个的子集(包括重复项)? [英] C# LINQ method to determine if array is subset of another (including duplicates)?

查看:103
本文介绍了C#LINQ方法确定数组是否为另一个的子集(包括重复项)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑两个数组:

int[] a1 = new int[] { 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10 };
int[] a2 = new int[] { 1, 3, 4, 7, 5, 10, 1 };

我希望能够确定a2是否是a1的子集,考虑重复项的数量.

I want to be able to determine if a2 is a subset of a1, considering the number of duplicate items.

换句话说,如果a1具有三个"1",而a2具有四个"1",则a2不是a1的子集.但是,如果a1包含三个"1",则只要a2中包含三个或更少的"1",就应将其视为子集.

In other words, if a1 has three "1"'s, and a2 has four "1"'s, then a2 is not a subset of a1. However, if a1 contains three "1"'s, then as long as a2 has three or less "1"'s in it, it should be considered a subset.

使用LINQ的"Intersect"语句的方法不起作用,因为在两个均包含三个"1"的两个数组上执行Intersect会返回仅包含一个"1"的数组.不管这两个数组中有多少个"1",它都将执行此操作;它只是在查看该项目是否同时存在于两个数组中.

Methods using LINQ's "Intersect" statement don't work, as doing Intersect on two arrays each containing three "1"'s returns an array with just a single "1". It will do this regardless of how many "1"'s are in either array; it's only looking to see if the item exists in both arrays.

示例(基于上面的数组a1):

Examples (based on array a1 above):

int[] a2 = new int[] { 1, 3, 4, 7, 5, 10, 1 };   // True
int[] a3 = new int[] { 1 };                      // True
int[] a4 = new int[] { 9, 3, 5, 1, 1, 10, 10 };  // True
int[] a5 = new int[] { 1, 1, 1, 1, 10, 10 };     // False
int[] a6 = new int[] { 1, 2, 3, 3, 4, 5 };       // False
int[] a7 = new int[] { 10, 10, 10 };             // False
int[] a8 = new int[0];                           // False

有没有办法使用LINQ来达到预期的结果?

Is there a way to accomplish the desired result using LINQ?

我已经考虑过通过将所有数组转换为列表,迭代并从列表中删除项的方法来完成此操作.我只是好奇是否有更优雅的解决方案.

I've considered a rather ugly way of doing this by converting all the arrays into lists, iterating, and removing items from the lists. I was just curious if there is a more elegant solution.

推荐答案

对我来说这很简单:

var l1 = a1.ToLookup(x => x);
var l2 = a2.ToLookup(x => x);

var check = l2.All(xs => xs.Count() <= l1[xs.Key].Count());

这适用于您所有示例数据,但空集除外-我认为应该将其视为子集,因此我认为这对所有数据都适用.

This works with all of you example data, except the empty set - which I think should be considered a subset, so I think this should work fine for all of them.

这篇关于C#LINQ方法确定数组是否为另一个的子集(包括重复项)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆