c# - 使用检查查找超集的 Linq 查询
问题描述
我想查询一个包含一些重复文本的列表,并且有/没有 id 值。
我有两个条件要匹配,
- 选择任何 2 个具有 ID 的相同[text, type]组,否则选择唯一的一个。
- 任意 2 个文本,其中一个包含另一个,则选择超集文本。[唱歌,跳舞唱歌=>跳舞唱歌]
Type Text Id Name John Name John 22 Name John Smith 2548 Hobby Singing Hobby Dancing Singing School XYZ School XYZ 242
预期输出:
Type Text Id Name John Smith 2548 Hobby Dancing Singing School XYZ 242
解决方案
这很丑陋,但它有效:
class Program
{
static void Main(string[] args)
{
List<Record> records = BuildTestData();
List<Record> deduped = DeDupe(records);
Console.Clear();
foreach (Record r in deduped)
Console.WriteLine($"Type:{r.Typ}, Text:{r.Txt}, ID:{r.ID} ");
Console.ReadKey();
}
static List<Record> DeDupe(List<Record> dupes)
{
List<Record> excludes = new List<Record>();
excludes.AddRange(dupes.GroupBy(x => new { x.Typ, x.Txt }).Where(y => y.Count() > 1).SelectMany(z => z.Where(a => string.IsNullOrEmpty(a.ID))));
excludes.AddRange(dupes.Where(x => !excludes.Any(y => x == y) && dupes.Any(z => x != z && x.Txt != z.Txt && z.Txt.Contains(x.Txt))));
return dupes.Where(x => !excludes.Any(y => x == y)).ToList();
}
static List<Record> BuildTestData()
{
return new List<Record>
{
new Record { Typ = "Name", Txt = "John", ID = null},
new Record { Typ = "Name", Txt = "John", ID = "22"},
new Record { Typ = "Name", Txt = "John Smith", ID = "2548"},
new Record { Typ = "Hobby", Txt = "Singing", ID = null},
new Record { Typ = "Hobby", Txt = "Dancing Singing", ID = null},
new Record { Typ = "School", Txt = "XYZ", ID = null},
new Record { Typ = "School", Txt = "XYZ", ID = "242"},
};
}
}
public class Record
{
public string Typ { get; set; }
public string Txt { get; set; }
public string ID { get; set; }
}
推荐阅读
- acumatica - Acumatica Create PO Receipt via API setting the detail line po data does not create the PO Receipt Orders Link
- azure - Changing the format of BLOB storage in Azure
- javascript - document.getElementById 始终返回 null
- tailwind-css - TailwindCSS:禁用的变体不起作用
- actionscript-3 - adobe animate cc中的action script 3.0,如何解决点击网页上的go
- java - 过滤掉一个数组
- azure - 格式化 Powershell 脚本对象输出?
- exception - 在不使用 concat 的情况下连接 Clojure 中的列表
- google-apps-script - 是否可以为每个新的谷歌文档添加相同的自定义菜单?目标是使本地脚本功能类似于已安装的应用程序
- python - twilio:从无提高 KeyError(key)