简体   繁体   English

使用linq将逗号分隔的字符串与整数列表匹配,然后返回新对象

[英]Match a comma delimited string to an integer list using linq and return the new objects

Edit: I changed my inputs from a 编辑:我改变了我的输入

List<string>

to a List<int> . List<int> They should always be valid integers now, no empty/null etc. 现在,它们应该始终是有效的整数,不能为空/空等。

I currently have a 6 item list, the items consistent of integers. 我目前有6个项目列表,这些项目与整数一致。

I also have an object that contains a coma delimited string of integers. 我也有一个包含逗号分隔的整数字符串的对象。 I'm trying to match the inputs to this list. 我正在尝试将输入匹配到此列表。


For example 例如

Inputs could be, 1000,2000,3000 The object contains 1000,2000,3000,4000 I would want this to match. 输入可能是1000,2000,3000,该对象包含1000,2000,3000,4000,我希望它与之匹配。

If my input is 1000,2000,3000,4000 and my object only contains 1000,2000,3000 -> it should not match. 如果我的输入是1000,2000,3000,4000,而我的对象仅包含1000,2000,3000->它应该不匹配。

Here's my current code to create the object using linq to xml. 这是我当前使用linq to xml创建对象的代码。 "TaxUnitIdList" is the comma delimited string. “ TaxUnitIdList”是逗号分隔的字符串。 (This is when my inputs were strings) (这是我的输入为字符串时)

var   obj = (from tug in tugElem.Descendants("CodeData")
select new TaxUnitGroups
{
    Code = (string)tug.Attribute("code"),
    CodeID = (string)tug.Attribute("codeid"),
    Desc = (string)tug.Attribute("desc"),
    TaxUnitIdList = (string)tug.Attribute("taxunits")
});

I'm thinking something along the following or a join (which I could not get to work) this is failing me due to the where wanting a boolean (which makes sense) 我在考虑以下内容或联接(无法正常工作),这使我失败了,因为需要布尔值的地方(这很有意义)

var matchedTugs = (from tug in tugElem.Descendants("CodeData")
    let TaxUnitIdList = (string)tug.Attribute("taxunits")
    let taxArr = TaxUnitIdList.Split(',').Select(int.Parse)
    where taxArr.Contains(inputTaxUnits.All()) //This is where I screw up
    select new TaxUnitGroups
    {
        Code = (string)tug.Attribute("code"),
        CodeID = (string)tug.Attribute("codeid"),
        Desc = (string)tug.Attribute("desc"),
        TaxUnitIdList = (string)tug.Attribute("taxunits")
    }).ToList();  

Try this in the Where clause: 在Where子句中尝试以下操作:

TaxUnitIdList.Split(',')
    .Select(s => int.Parse(s))
    .Except(inputTaxUnits.Where(s=>int.TryParse(s, out tempInteger))
        .Select(s=>int.Parse(s)))
    .Any();

Basically, we want to covert the TaxUnitId list into an integer array, convert the input list into a good (tryparse) input array as well, find the difference and verify that the result is 0. 基本上,我们希望将TaxUnitId列表转换为整数数组, TaxUnitId输入列表也转换为良好的 (tryparse)输入数组,找出差值并验证结果是否为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM