Monday, August 17, 2009

Removing blank and duplicated entries

Scenario:
Often for manupulations I need to removing blank and duplicated entries.

Solution:
Here's i do it using LINQ

Code:

using System.Linq;
using System.Text.RegularExpressions;

// array of string
var concatinationOperator = ";#";
var draftValues = ";#value1;#value2;#value2;#;#value3;#";

// extracting values in another variable based on delimiter
var draftValuesArray = Regex.Split(draftValues, concatinationOperator);

// c=>c.Length>0 will ensure removal of blank entries
// Distinct() funtion will only take keep unique values
var draftValuesArrayDistinctAndNonBlank = draftValuesArray.Where(c=> c.Length>0 ).Distinct();

// concating again to return the final string
var finalValueArray = from s in draftValueArrayDistinctAndNonBlank
select s + concatinationOperator;

var finalValues = string.Join(concatinationOperator, finalValueArray.ToArray());

0 comments: