简体   繁体   中英

select unique list from list<string> using linq and substring c#

I have

List<string> fileListServiceLine;

below are the values in the list;

A073662937EMC900200202EST PT-OFF/OPD VISIT          0016224DIAGNOSTIC LAB TEST
A098281448EMC900700103EST PT-OFF/OPD VISIT          0016111SELFCARE TRAINING   

I have an identifier

string identifier = EMC9002002;

I get this identifier value from config file.

In my practical case scenario I get more than 2 values in the list string mentioned above.

I am trying to filter the list fileListServiceLine and get only those values which match identifier. identifier will be present in one of the items in the fileListServiceLine list and only one list item will be a matching case.

I am trying the below code it is not giving the exact result.

var servLineRecords = fileListServiceLine.GroupBy(s => s.Substring(location.ServiceLineIdentifierStart - 1, location.ServiceLineIdentifierLength) == identifier );

location.ServiceLineIdentifierStart and location.ServiceLineIdentifierLength I will get above values from config file to locate the exact position of identifer matching value.

Thanks In Advance.

使用此linq语句:

var servLineRecords = fileListServiceLine.Where(s => s.ToLower().Contains(identifier.ToLower())).FirstOrDefault();

You need to use the Contains() method instead like below. Since you know there will be only one value matching the identifier you can use First() and get the first item

fileListServiceLine.Where(s => s.Contains(identifier)).First();

In case, you want to do a case insensitive search then use IndexOf() method instead like

fileListServiceLine.SingleOrDefault(s => s.IndexOf(identifier, StringComparison.OrdinalIgnoreCase) >= 0);

You can use either Single or SingleOrDefault . eg,

fileListServiceLine.Single(s => s.Contains(identifier));

Single will throw an exception if there isn't exactly one match, whereas SingleOrDefault will instead return null .

I would recommend using Contains() combined with some lower-casing using ToLower() on both of the strings to find the matching element. FirstOrDefault() returns default value if no element is found.

var record = fileListServiceLine.Where(s => s.ToLower().Contains(identifier.ToLower())).FirstOrDefault();

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