简体   繁体   中英

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> . They should always be valid integers now, no empty/null etc.

I currently have a 6 item list, the items consistent of integers.

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.

If my input is 1000,2000,3000,4000 and my object only contains 1000,2000,3000 -> it should not match.

Here's my current code to create the object using linq to xml. "TaxUnitIdList" is the comma delimited string. (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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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