最匹配的字段值

时间:2010-09-22 07:17:06

标签: c# linq datatable

我有DataTable。我也可以使用Linq。 在DataTable中有许多列和行。其中一列称为 feedCode 。它的类型是string。在database中,它的长度为7 varchar,可以为空。

feedCode 可能包含 9051245,9051246,9051247,9031454,9021447 的值。

方法必须返回最匹配的(在本例中以905开头)值 905 (字符串的前3个字符)?

感谢。

2 个答案:

答案 0 :(得分:1)

也许我没有正确理解你的问题,但也许这将是你的起点:

//The feedCodes (i put one in two times, to have one appearing most often)
var values = new string[] { "9051245", "9051246", "9051247", null, "", "9051245", "9031454", "9021447" };

//Just filter the list for filled up values
var query = values.Where(value => !String.IsNullOrEmpty(value))
                    //and group them by their starting text
                  .GroupBy(value => value.Substring(0, 3))
                    //order by the most occuring group first
                  .OrderByDescending(group => group.Count());

//Iterate over all groups or just take the first one with query.First() or query.FirstOrDefault()
foreach (var group in query)
{
    Console.WriteLine(group.Key + "  Count: " + group.Count());
}

答案 1 :(得分:1)

尝试使用此代码:

var feedCodes = new string[] { "9051245", "9051246", "9051247", "9051245", "9031454", "9021447" };

var mostOccuring = feedCodes.Where(feedCode => feedCode != null)
    .GroupBy(feedCode => feedCode.Length < 3 ? feedCode : feedCode.Substring(0, 3))
    .OrderByDescending(group => group.Count())
    .FirstOrDefault();

if(mostOccuring == null)
{
    //some exception handling
}
else
{
    //process mostoccuring.Key
}

此代码还处理长度小于3的源代码(即使是空字符串)。如果您不想使用它们,只需在where语句中过滤掉它们。

相关问题