简体   繁体   English

从列表中选择唯一列表 <string> 使用linq和子字符串C#

[英]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. 我试图过滤列表fileListServiceLine并仅获取那些与标识符匹配的值。 identifier will be present in one of the items in the fileListServiceLine list and only one list item will be a matching case. 标识符将出现在fileListServiceLine列表中的一项中,并且只有一个列表项是匹配的大小写。

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. location.ServiceLineIdentifierStart和location.ServiceLineIdentifierLength我将从配置文件中获取上述值,以找到identifer匹配值的确切位置。

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. 您需要改为使用Contains()方法,如下所示。 Since you know there will be only one value matching the identifier you can use First() and get the first item 因为您知道只有一个与标识符匹配的值,所以您可以使用First()并获得第一项

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

In case, you want to do a case insensitive search then use IndexOf() method instead like 如果要进行不区分大小写的搜索,请改用IndexOf()方法,例如

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

You can use either Single or SingleOrDefault . 您可以使用SingleSingleOrDefault 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 . 如果不完全匹配, Single将引发异常,而SingleOrDefault将返回null

I would recommend using Contains() combined with some lower-casing using ToLower() on both of the strings to find the matching element. 我建议将Contains()与在两个字符串上使用ToLower()低级外壳结合使用,以找到匹配的元素。 FirstOrDefault() returns default value if no element is found. 如果未找到任何元素,则FirstOrDefault()返回默认值。

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

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

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